Webpack babel-loader runtime: Module build failed: TypeError: this.setDynamic is not a function

Webpack babel-loader runtime: Module build failed: TypeError: this.setDynamic is not a function

我正在尝试将 babel-loaderbabel-plugin-transform-runtime 一起使用。

我已按照以下网址的说明进行操作: https://github.com/babel/babel-loader#babel-is-injecting-helpers-into-each-file-and-bloating-my-code

相关代码:

rules: [
  // the 'transform-runtime' plugin tells babel to require the runtime
  // instead of inlining it.
  {
    test: /\.js$/,
    exclude: /(node_modules|bower_components)/,
    use: {
      loader: 'babel-loader',
      options: {
        presets: ['@babel/preset-env'],
        plugins: ['@babel/transform-runtime']
      }
    }
  }
]

构建时出现以下错误:

Module build failed: Error: Cannot find module '@babel/plugin-transform-runtime'

如果我将插件名称更改为:plugins: ['transform-runtime'],我会收到以下错误:

Module build failed: TypeError: this.setDynamic is not a function

有什么问题?

您的 webpack 条目看起来与示例相同,所以我想知道如果您使用 .babelrc.

会发生什么
{
   "plugins": ["transform-runtime"]
}

您是否也安装了 env 预设?

经过一番努力,我找到了正确的方法。

Tl;dr

如果你安装了新的 babel 加载器,你应该加载新的 babel 插件。

全文

官方文档中的安装: npm install babel-loader@8.0.0-beta.0 @babel/core @babel/preset-env webpack

在 github 页面中,这些是 runtime 插件的说明:

NOTE: You must run npm install babel-plugin-transform-runtime --save-dev to include this in your project and babel-runtime itself as a dependency with npm install babel-runtime --save.

相反,您应该像这样使用新版本: npm install --save-dev @babel/plugin-transform-runtime npm install --save @babel/runtime

然后它将与文档中的配置一起工作。

首先,正如@yccteam 指出的那样,需要安装

npm install --save-dev @babel/plugin-transform-runtime
npm install --save @babel/runtime

.babelrc 文件应该有

{
  "presets": [
    ["@babel/preset-env", {
      "debug": false,
      "modules": false,
      "useBuiltIns": false
    }], 
    "@babel/preset-react"
  ],
  "plugins": [
    "@babel/syntax-dynamic-import",
    "@babel/plugin-transform-runtime",
    [ "@babel/plugin-proposal-class-properties", { "loose": true } ],
    "@babel/transform-async-to-generator"
  ],
  "env": {
    "production": {
      "presets": ["react-optimize"]
    }
  }
}

webpack.js 文件应如下所示

 module: {
  rules: [
    {
      test: /(\.js[\S]{0,1})$/i,
      exclude: /node_modules/,
      loader: 'babel-loader',
      query: {
        presets: ['@babel/preset-react', '@babel/preset-env'],
        plugins: ['@babel/proposal-class-properties']
      },
    },
    ...