babel-preset-env在webpack中不能转译箭头函数

10

我正在使用webpack和babel,尝试使箭头函数在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
};

你需要一个 polyfill。Core-js 或 babel-polyfill 都可以完成这项工作。 - Dimitar
3个回答

3
如果您正在使用 Babel 7,.babelrc 的行为已经发生了变化
我的建议是放弃 .babelrc 并将配置放在您的 webpack 配置文件中。
此外,您需要从配置中删除 exclude: /node_modules/,或者添加一些条件,以便不排除使用浏览器不兼容代码的任何库(例如,如果您想使用 IE,则需要添加箭头函数)。
个人建议是完全删除 exclude,并且没有注意到速度或大小的降低。

2

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

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

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


1
感谢您。在我看来,这应该被标记为答案。 - Partha P. Das

0

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

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

这里是指定浏览器集的所有可能方式


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接