包含 babel polyfill,但 forEach 仍然无法在 IE11 的 NodeLists 上工作

2023-12-22

我已经让 Webpack 与 Babel 一起工作,并包括 @babel/polyfill,但 IE11 在尝试使用时仍然抛出 SCRIPT438 错误.forEach on a NodeList.

这是我的package.json

{
  ...
  "scripts": {
    "build:js": "webpack --config ./_build/webpack.config.js"
  },
  ...
  "browserslist": [
    "IE 11",
    "last 3 versions",
    "not IE < 11"
  ],
  "babel": {
    "presets": [
      [
        "@babel/preset-env",
        {
          "useBuiltIns": "usage"
        }
      ]
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.1.6",
    "@babel/preset-env": "^7.1.6",
    "babel-loader": "^8.0.4",
    "webpack": "^4.25.1",
    "webpack-cli": "^3.1.2"
  },
  "dependencies": {
    "@babel/polyfill": "^7.0.0"
  }
}

My webpack.config.js:

const path = require('path');
const webpack = require('webpack');

module.exports = (env, argv) => {

  const javascript = {
    test: /\.js$/,
    use: {
      loader: 'babel-loader'
    }
  };

  // config object
  const config = {
    entry: {
      main: './_src/js/main.js',
    },
    devtool: 'source-map',
    output: {
      path: path.resolve(__dirname, '../js'),
      filename: '[name].js',
    },
    module: {
      rules: [javascript]
    }
  }

  return config;
}

最后/_src/main.js我正在运行 webpack 和 babel:

const testList = document.querySelectorAll('.test-list li');

testList.forEach(item => {
  console.log(item.innerHTML);
})

文档位于https://babeljs.io/docs/en/babel-polyfill https://babeljs.io/docs/en/babel-polyfill说你不需要import or require polyfill通过 Webpack 加载它时useBuiltIns: "usage"。但即使我删除该选项并手动导入顶部的整个填充main.js(使我的包变得巨大),它在 IE11 中仍然出错。

那么...我做错了什么?


Update:从 Babel 7.4.0 开始,Babel 已改用core-js直接而不是用它包裹@babel/polyfill. core-js已经填充了forEach on NodeList,因此不再需要额外的填充。


babel-polyfill 不会对缺少的 Web API/原型方法进行 Polyfill,例如NodeList.prototype.forEach.

另请注意,您的问题标题具有误导性NodeList.prototype.forEach不是 ES6 特性。forEach在可迭代集合上目前只有一个候选人推荐(截至 2018 年 8 月)。

只需在 Javascript 的顶层包含您自己的 polyfill 即可:

if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = Array.prototype.forEach;
}

一旦 core-js 3 稳定,这可能会改变:https://github.com/zloirock/core-js/issues/329 https://github.com/zloirock/core-js/issues/329

如果您开始采用 ES6 时代使用的常见模式,您也可以不使用任何 polyfill:

const testList = [...document.querySelectorAll('.test-list li')];

or

const testList = Array.from(document.querySelectorAll('.test-list li'));

您的另一个选择是使用for...of反而:

const lis = document.querySelectorAll('.test-list li');
for (const li of lis) {
  // li.addEventListener(...) or whatever
}

最后,你还可以采用常见的 ES5 模式:

var testList = document.querySelectorAll('.test-list li');
Array.prototype.forEach.call(testList, function(li) { /*whatever*/ });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

包含 babel polyfill,但 forEach 仍然无法在 IE11 的 NodeLists 上工作 的相关文章

随机推荐