3

I'm trying to get babel-polyfill working with for a library but I'm getting the following error:

TypeError: Cannot read property '_babelPolyfill' of undefined
at Object.<anonymous> (/Users/foo/webpack-library-starter/lib/library.js:73:6)
...

I'm using webpack-library-starter as my template.

Full replication details:

git clone https://github.com/krasimir/webpack-library-starter.git
cd webpack-library-starter
npm i
npm i --save babel-polyfill

Tried both adding import 'babel-polyfill' to the beginning of "src/index.js" and not having it.

Add 'babel-polyfill' to "webpack.config.js":

  entry: ['babel-polyfill', __dirname + '/src/index.js'],

Then build and test:

npm run dev
npm run build
npm test
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
Nelson Yeung
  • 3,262
  • 3
  • 19
  • 29

1 Answers1

4

This project template is somewhat ill-advised. Webpack creates packages that are meant to be loaded in a browser environment. Mocha, however, runs in node. So you have to take into account what transmogrifications webpack does to the bundled code and what happens when this code is fed back into node.

When babel-polyfill is bundled by webpack, there's this implicit assumption that the bundle will be loaded in a browser and some specific globals (namely, that this in unbound functions refers to window) will be there.

The proper way to load babel-polyfill in node is with node's own require. For example, change the test script in package.json to:

"test": "mocha --compilers js:babel-core/register --colors -r babel-polyfill ./test/*.spec.js"

Your library's bundle should not load babel-polyfill at all though. If your library initializes babel-polyfill and someone includes your library into their project which also initializes babel-polyfill, they'll get an exception stating, quote, "only one instance of babel-polyfill is allowed".

Stefan Dragnev
  • 14,143
  • 6
  • 48
  • 52
  • "Your library's bundle should not load babel-polyfill at all though. ..." A very important point that I completely missed! Thank you very much. – Nelson Yeung Jan 16 '17 at 11:03