Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Object.assign() require a polyfill when babel-loader is being used?

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()?

like image 897
Collin Allen Avatar asked Aug 21 '15 19:08

Collin Allen


People also ask

Why is Babel polyfill?

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.

Does Babel automatically polyfill?

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 ).

Do I need Babel polyfill?

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.


1 Answers

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.

like image 77
loganfsmyth Avatar answered Sep 21 '22 12:09

loganfsmyth