javascript - 对象不支持属性或方法 'assign'

标签 javascript webpack babeljs

我设置 webpack + babel 配置

webpack.config.js

...
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
...

.babelrc

{
  "plugins": ["lodash", "transform-object-rest-spread"],
  "presets": [
    ["env", {
      "targets": [
        "> 4%",
        "ie 11",
        "safari 8"
      ]
    }],
    "react",
    "react-optimize"
  ],
  "env": {
    "test": {
      "presets": ["es2015", "react"]
    }
  }
}

在 google chrome 中一切正常,但在 IE 11i 中出现错误

Object doesn't support property or method 'assign'

最佳答案

您还需要添加对象分配转换 检查https://babeljs.io/docs/plugins/transform-object-assign/

另请注意,最好的做法是包含一个 polyfill。 MDN 通常会给出 ES2015 特性的 polyfill 代码。检查https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

为了记录,它是:

if (typeof Object.assign != 'function') {
  Object.assign = function(target, varArgs) { // .length of function is 2
    '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;
  };
}

您希望在不支持 Object.assign 的浏览器的应用中包含此代码。上面提到的 Babel 转换插件在构建应用程序而不是库时也推荐这种方法。

关于javascript - 对象不支持属性或方法 'assign',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43823967/

相关文章:

javascript - 显示带有 openlayers 和外部 geojson 文件的简单图标

javascript - Node.js 需要 webpack 模块

javascript - 使用 babel 为 React 应用程序转译 jsx

javascript - 如何在 Babel 中将 * 导出为命名空间?

javascript - 在 ajax 调用中传递 php 值

javascript - 将 pMathML 转换为 cMathML 的算法/工具?

javascript - Indy TIdHTTPServer OnCommandGet html 中的 javascript 未执行

npm - 无法在单 SPA 应用程序中启动微前端应用程序

reactjs - 未定义的 css 模块类名

javascript - Ant design - 有没有办法获得我实际使用的样式?