14

我正在尝试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

问题是什么?

4

3 回答 3

13

经过一番挣扎,我找到了正确的方法。

Tl;博士

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

全文

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

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

注意:您必须运行 npm install babel-plugin-transform-runtime --save-dev 以将其包含在您的项目中,并且 babel-runtime 本身作为 npm install babel-runtime --save 的依赖项。

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

然后它将与文档中的配置一起使用。

于 2018-01-21T15:21:38.693 回答
8

首先,正如@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']
      },
    },
    ...
于 2018-12-09T21:03:04.063 回答
0

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

{
   "plugins": ["transform-runtime"]
}

您是否也安装了 env 预设?

于 2018-01-21T11:41:34.007 回答