使用Babel为IE11移植ES6

时间:2019-06-04 15:24:19

标签: webpack babeljs

我是babel的新手,正在尝试转换我的es6代码以与IE11一起使用。但是,当我在IE11中运行代码时,我收到有关forEach代码的js错误。根据我的读物,我需要添加预设@babel/preset-env。我将其添加到配置文件中,所以我不确定为什么它没有转译那些forEach调用。

const path = require('path');

module.exports = {
    entry: {
        setupForm: "./Scripts/es6/setupForm.js",
        prelimForm: "./Scripts/es6/prelimForm.js"
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, './Scripts/build'),
    },
    module: {
        rules: [{
            loader: 'babel-loader',
            test: /\.js$/,
            exclude: /node_modules/,
            query: {
                presets: ['@babel/preset-env']
            }
        }]
    }
}

我以为也许我需要另外将babel polyfill.js引用为discussed here,所以我将其添加到页面中,但是,关于 Object not支持属性或方法“ forEach”

这是我的package.json文件。

{
  "name": "OurSite",
  "version": "1.0.0",
  "description": "",
  "main": "map_embed.js",
  "directories": {
    "doc": "docs"
  },
  "scripts": {
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.4.5",
    "@babel/preset-env": "^7.4.5",
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.6",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "webpack": "^4.32.2",
    "webpack-cli": "^3.3.2"
  },
  "babel": {
    "presets": [
      "env"
    ]
  },
  "dependencies": {}
}

2 个答案:

答案 0 :(得分:8)

从Babel 7.4.0开始,@babel/polyfillcore-js软件包已被弃用。

https://babeljs.io/docs/en/babel-polyfill#docsNav

包含在webpack中

regenerator

或在您的js顶部包含

module.exports = {
  entry: {
    main: [
      'core-js/stable',
      'regenerator-runtime/runtime',
      'src/main.js'
    ]
  }
}

答案 1 :(得分:0)

这是您应该做的:

  • 安装@babel/polyfill
  • @babel/polyfill中包含entry(如果您有多个条目,并且您不打算将两者都放在同一页面上,请在两个页面中都包含polyfill)
  • 确保所有babel软件包都具有相同的主要版本,即7.x.x(不用担心babel-loader-实际上是webpack软件包,而不是babel软件包) 。

Webpack

module.exports = {
    ...
    entry: {
        setupForm: ["@babel/polyfill", "./Scripts/es6/setupForm.js"],
        prelimForm: ["@babel/polyfill", "./Scripts/es6/prelimForm.js"]
    },
    ...
}

package.json

{
  ...
  "devDependencies": {
    "@babel/core": "^7.4.5",
    "@babel/preset-env": "^7.4.5",
    "@babel/polyfill": "^7.4.4",
    "babel-loader": "^8.0.6",
    "webpack": "^4.32.2",
    "webpack-cli": "^3.3.2"
  },
  ...
}