2015-08-21 93 views
48

我试图通过与通天编译的WebPack一个ES6的Web应用程序使用Object.assign(),但我得到一个错误:为什么在使用babel-loader时Object.assign()需要填充?

Uncaught TypeError: Object.assign is not a function 

我已经使用babel-loader到transpile ES6到ES5,所以我所有的其他ES6代码正在工作。然而,Object.assign()只有在我的代码库中还有import "babel-core/polyfill"后才能正常工作。我看到我也可以修复这个by importing babel-runtime,但是我想了解为什么Object.assign()需要比babel-loader更高的性能 - 不应该babel-loader预处理所有内容,包括Object.assign()

+10

只是说明了未来的读者:在填充工具,叫做“通天核心/ polyfill“在时间th在这个问题上写了,现在是“babel-polyfill”,按[文档](https://babeljs.io/docs/usage/polyfill/)。 –

回答

45

巴贝尔,通过babel-loader,在ES6 语法 transpiles差异。 Babel本身在ES6标准库功能(例如Object.assign)中完全没有添加任何内容。加载填充为你加载一个单独的填充core-js,但你可以加载任何你想要的填充。

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

+0

很好的解释!谢谢! –

3

如果你去兼容性,你可以看到IE 11是不支持Web和移动object.assign。它也为你提供了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; 
    }; 
} 

如果使用巴贝尔

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

如果使用NPM

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

相关问题