Why does Object.assign not appear to work on Safar

2019-02-13 12:39发布

问题:

We're writing an app using webpack and babel-core 5.8.25.

At one point in time, this happens:

someArray.map(item => {
  const updatedItem = Object.assign({}, item); // silently fails here... doesn't even continue the code

  updatedItem.prop = 'something cool';
});

This is obviously compiled before hitting the browser. It works in the latest version of Chrome and the latest version of iOS Safari, but in Safari 8.0.7, it fails silently (no error thrown... just doesn't go past that line).

This, however, works as expected (using lodash):

someArray.map(item => {
  const updatedItem = _.extend({}, item); // the important part

  updatedItem.prop = 'something cool';
});

Any idea? I tried poking around the internet regarding this, but to no avail.

回答1:

Object.assign works in Chrome because Chrome supports it natively. babel-loader on its own only converts ES6 syntax to ES5 syntax, it does not do anything to make ES6 library functionality available. The easiest way to do that with Webpack is to change your config from something like

entry: 'app.js'

to

entry: ['babel-core/polyfill', 'app.js']

// Or with Babel 6:
entry: ['babel-polyfill', 'app.js']

so that Webpack will also bundle and run the polyfill before executing your application. Babel provides /polyfill as an easy way to load the polfill, but it is optional because not everyone wants to use it, and because there are many polyfills available and the one Babel uses, core-js is just one of many.