Webpack + Babel - 转译对象箭头函数无法正常工作。

7

我正在尝试使用babel-loader将webpack(5)配置为将代码转译为ES5。不幸的是,输出结果不一致,基本上可以分为两部分:

  1. 某些polyfills:

  2. 我的代码:

正如您所看到的,第一部分包含箭头函数,而第二部分则不包含。

我尝试在我的.babelrc文件中添加@babel/plugin-proposal-class-properties@babel/plugin-transform-arrow-functions,但是启用了调试后发现class-properties是丢失的。

我必须承认,我不确定class-properties是否是问题所在,但是在谷歌上花费数小时后,这是我最好的猜测,所以也许我对问题的源头有误解。

webpack文件:

export default {
  entry: './src/index.js',
  mode: 'production',
  output: {
    path: path.resolve(__dirname, '..', '..', 'dist'),
    filename: 'bundle.prod.js'
  },
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  }
}

.babelrc 文件:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "corejs": {
          "version": 3
        },
        "useBuiltIns": "usage",
        "debug": true
      }
    ]
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-transform-arrow-functions"
  ]
}

Node依赖:

"@babel/core": "7.11.6",
"@babel/plugin-proposal-class-properties": "7.10.4",
"@babel/plugin-transform-arrow-functions": "7.10.4",
"@babel/preset-env": "7.11.5",
"@babel/register": "7.11.5",
"babel-loader": "8.1.0",
"core-js": "3.6.5",
"webpack": "5.0.0",
"webpack-cli": "4.0.0",
"webpack-merge": "5.2.0"
2个回答

22

我曾经遇到过与webpack v5类似的问题.

Bootstrap中的箭头函数

我需要修改webpack配置并添加:

target: ['es5']

        module: {
            rules: [.....]
        },
        resolve: {
            extensions: [".ts", ".tsx", ".js"]
        },
        target: ['es5']

Weback V5 目标配置


7
在浏览器环境中使用时,您应该添加 target: ['web', 'es5'] - Guntarss
1
此Webpack构建使用的tsconfig文件需要在其compilerOptions中设置"target": "ES5" - Andrew Koster
当引用外部库时,例如 "external": {jquery: "jQuery"},您还需要在输出中指定 chunkFormat"output": {..., "chunkFormat": "array-push"} - Serge S.

0

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