3

I have this in my webpack.config.js to create two different outputs from two sources:

module.exports = {
  entry: {
    'dist/index.js': ['babel-polyfill', './src/Component.jsx'],
    'example/bundle.js': ['babel-polyfill', './src/Page.jsx'],
  },
  output: {
    path: './',
    filename: '[name]',
  },
  ...

Compiling it with webpack works just fine, but if I load index.js in a browser I get this error:

Uncaught Error: only one instance of babel-polyfill is allowed

I need babel-polyfill for both outputs. What can I do?

Rotareti
  • 49,483
  • 23
  • 112
  • 108
  • Could you clarify why specifically you want it in both entry points? It's pretty large, you really don't want to be loading it twice without a really good reason. – loganfsmyth Sep 06 '16 at 07:12
  • 1
    Sure! I want to create a react component as a npm package (*dist/index.js*). In order to develop the component in isolation, I created a small page (*example/bundle.js*), which loads the component and displays the result. When I work on the component I can see the results in the browser on that little page. The overhead wouldn't be a problem because the code remains small in most cases. – Rotareti Sep 06 '16 at 11:35

2 Answers2

4

When developing a library (as opposed to an application), the Babel team does not recommend including babel-polyfill in your library. We recommend either:

  1. Assume the ES6 globals are present, thus you'd instruct your library users to load babel-polyfill in their own codebase.
  2. Use babel-runtime by enabling babel-plugin-transform-runtime, which attempts to analyze your code to figure out what ES6 library functionality you are using, then rewrites the code to load the polyfilled logic from babel-runtime instead of from the global scope. One downside of this approach is that it has no way to polyfill new .prototype methods like Array.prototype.find since it can't know if foo.find is an array.

So my recommendation would be to remove babel-polyfill from your dist/index.js bundle entirely.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • What option do you recommend? Also if I want to load it independently, how would you recommend to do it? – shinzou Mar 29 '17 at 10:55
  • To make a js file with just `import "babel-polyfill";` and add its entry and load it first? – shinzou Mar 29 '17 at 10:58
0

Use idempotent-babel-polyfill

import 'idempotent-babel-polyfill';

https://github.com/codejamninja/idempotent-babel-polyfill

Clay Risser
  • 3,272
  • 1
  • 25
  • 28