babel-preset-env无法使用webpack转换箭头功能

时间:2018-08-03 09:25:58

标签: javascript webpack babel

我将babel与webpack一起使用,我试图使箭头功能与Internet Explorer一起使用,但是我无法使其正常工作。

这是我的 package.json 开发依赖项:

"devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-preset-env": "^1.7.0",
    "webpack": "^3.12.0",
    "webpack-cli": "^3.1.0"
  }

这是我的webpack.config.js:

module.exports = {
  entry: ['./chat.js'],
  devtool: 'source-map',
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "chat.js"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      }
    ]
  }  
};

我正在使用 .babelrc 的插件:

{
  "presets": ["env"],
  "plugins": ["transform-class-properties"]
}

我不知道自己在做什么错或缺少什么,但是我在Internet Explorer上收到以下语法错误:

DF.fn = () => {
        // Content
};

3 个答案:

答案 0 :(得分:1)

如果您使用的是Babel 7,则.babelrc has changed的行为。

我的建议是删除.babelrc并将配置放入Webpack配置中。

此外,您将需要从配置配置中删除exclude: /node_modules/,或添加一些条件以不排除任何使用浏览器不兼容代码的库(例如,如果要使用IE,则使用箭头功能)。

我个人完全删除了exclude,并没有发现速度或大小下降。

答案 1 :(得分:0)

您必须为构建指定目标浏览器。基于babel-preset-env,决定需要应用哪些转换。这是docs和配置示例

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 versions", "safari >= 7"]
      }
    }]
  ]
}

here是指定浏览器集的所有可能方法。

答案 2 :(得分:0)

对于使用 Webpack 5 的用户,您需要在 ouput.environment 配置中指定要转译的功能,如下所述:https://webpack.js.org/configuration/output/#outputenvironment

我使用的是差异化服务,因此我根据 modern 变量设置了所有标志(仅在为最近的浏览器构建时才设置为 true,这是 Chrome 的最后 5 个版本和Firefox 以及最近 2 个版本的 Safari、Edge 和 iOS)。

output: {
  // ... other configs
  environment: {
    arrowFunction: modern,
    bigIntLiteral: modern,
    const: modern,
    destructuring: modern,
    dynamicImport: modern,
    forOf: modern,
    module: modern,
  },
}

相关问题