为什么在使用babel-loader时Object.assign()需要polyfill?

Col*_*len 60 javascript ecmascript-6 webpack babeljs

我试图Object.assign()在Babel使用webpack编译的ES6 Web应用程序中使用,但是我收到一个错误:

Uncaught TypeError: Object.assign is not a function
Run Code Online (Sandbox Code Playgroud)

我已经babel-loader习惯将ES6转换为ES5,所以我所有的其他ES6代码都在工作.然而,Object.assign()只有import "babel-core/polyfill"在我的代码库之后才能工作.我看到我也可以通过导入babel-runtime来解决这个问题,但是我想了解为什么 Object.assign()需要的不仅仅是babel-loader执行 - 不应该babel-loader预处理所有内容,包括Object.assign()

log*_*yth 55

Babel,via babel-loader,转换了ES6 语法的差异.Babel本身在ES6标准库功能中没有任何补充(例如Object.assign).加载polyfill会core-js为您加载单独的polyfill ,但您可以加载所需的任何polyfill.

甚至一些语法转换依赖于特定的polyfill功能来加载,因为一些语法依赖于库代码中实现的算法和行为.http://babeljs.io/docs/learn-es2015/上的ES6功能列出了假定已加载的标准库功能.


Bre*_*ira 12

Object.assign()是一个新的API,它是ES6规范的一部分,所以它还没有在大多数浏览器中实现.请参阅:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

因此,当您导入时babel-core/polyfill,它会向此添加polyfill以及其他新API,以便您的ES6代码可以使用它们.

babel-loader 只是将ES6语法转换为ES5兼容代码的转换器.


Vel*_*tam 9

如果您转到兼容性,您可以看到对于object.assign,Web和Mobile都不支持IE 11.它还为您提供了pollyfill.

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;
  };
 }
Run Code Online (Sandbox Code Playgroud)

如果使用巴别塔

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

如果使用NPM

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