I'm attempting to use Object.assign()
in an ES6 web app compiled by Babel with webpack, but I'm getting an error:
Uncaught TypeError: Object.assign is not a function
I'm already using babel-loader
to transpile ES6 to ES5, so all my other ES6 code is working. Yet, Object.assign()
only works after I also import "babel-core/polyfill"
in my codebase. I see that I can also fix this by importing babel-runtime, but I'd like to understand why Object.assign()
requires more than what babel-loader
performs — shouldn't babel-loader
preprocess everything, including Object.assign()
?
Babel Polyfill adds support to the web browsers for features, which are not available. Babel compiles the code from recent ecma version to the one, which we want. It changes the syntax as per the preset, but cannot do anything for the objects or methods used.
Babel includes a polyfill that includes a custom regenerator runtime and core-js. This will emulate a full ES2015+ environment (no < Stage 4 proposals) and is intended to be used in an application rather than a library/tool. (this polyfill is automatically loaded when using babel-node ).
So long story short, just using babel is not enough for your application to work because all the latest Javascript features are not supported in all browsers. So to fix this problem, we need to use a polyfill.
Babel, via babel-loader
, transpiles differences in ES6 syntax. Babel on its own does absolutely nothing to add in ES6 standard library functionality (like Object.assign
). Loading the polyfill loads a separate polyfill core-js
for you, but you can load any polyfill you want.
Even some syntax conversions rely on specific polyfill functionality to be loads, since some syntax relies on algorithms and behaviors implemented in library code. The ES6 features on http://babeljs.io/docs/learn-es2015/ each list what standard library functionality are assumed to have been loaded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With