Why does Object.assign () require a polyfill when using the babel loader?

I am trying to use Object.assign() in an ES6 web application compiled by Babel with webpack, but I get an error:

 Uncaught TypeError: Object.assign is not a function 

I already use babel-loader to upgrade ES6 to ES5, so all my other ES6 codes work. However, Object.assign() only works after I also import "babel-core/polyfill" in my code base. I see that I can also fix this by importing babel-runtime , but I would like to understand why Object.assign() requires more than babel-loader does - shouldn 't babel-loader preprocess everything, including Object.assign() ?

+47
javascript ecmascript-6 webpack babeljs
Aug 21 '15 at 19:46
source share
3 answers

Babylon through babel-loader brings the differences in ES6 syntax. Babel itself adds absolutely nothing to the standard ES6 library functionality (e.g. Object.assign ). Downloading polyfill downloads a separate polyfill core-js for you, but you can download any polyfill you want.

Even some syntax conversions rely on certain polyfill functionality to be loaded, as some syntax is based on the algorithms and behavior implemented in the library code. ES6 elements at http://babeljs.io/docs/learn-es2015/ list which standard library functions are supposed to be loaded.

+44
Aug 21 '15 at 19:51
source share
— -

Object.assign() is a new API that is part of the ES6 specification, so it is not yet implemented in most browsers. See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Therefore, when you import babel-core/polyfill , it adds other new APIs to it so that your ES6 code can use them.

babel-loader is just a transpiler that converts ES6 syntax into ES5 compatible code.

+9
Aug 21 '15 at 19:57
source share

If you go to "Compatibility", you'll see that IE 11 is not supported on both the Web and Mobile for the object.assign object. It also gives you a fix.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

 if (typeof Object.assign != 'function') { Object.assign = function(target, varArgs) { 'use strict'; if (target == null) { // TypeError if undefined or null throw new TypeError('Cannot convert undefined or null to object'); } var to = Object(target); for (var index = 1; index < arguments.length; index++) { var nextSource = arguments[index]; if (nextSource != null) { // Skip over if undefined or null for (var nextKey in nextSource) { // Avoid bugs when hasOwnProperty is shadowed if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { to[nextKey] = nextSource[nextKey]; } } } } return to; }; } 

If you use babel

https://babeljs.io/docs/plugins/transform-object-assign/

If you are using NPM

https://www.npmjs.com/package/object-assign

+2
Feb 28 '17 at 8:37
source share



All Articles