Webpack babel 6 ES6 装饰器

Webpack babel 6 ES6 decorators

我有一个用 ES6 编写的项目,使用 webpack 作为我的打包器。大多数转译工作正常,但是当我尝试在任何地方包含装饰器时,出现此错误:

Decorators are not supported yet in 6.x pending proposal update.

我查看了 babel 问题跟踪器,但未能在其中找到任何内容,所以我假设我用错了。我的 webpack 配置(相关位):

loaders: [
  {
    loader: 'babel',
    exclude: /node_modules/,
    include: path.join(__dirname, 'src'),
    test: /\.jsx?$/,
    query: {
      plugins: ['transform-runtime'],
      presets: ['es2015', 'stage-0', 'react']
    }
  }
]

我对其他任何事情都没有问题,箭头函数、解构都可以正常工作,这是唯一不起作用的东西。

我知道我总是可以降级到 babel 5.8,我之前使用过它,但如果有任何方法可以让它在当前版本 (v6.2.0) 中运行,那将会有所帮助。

在 babeljs slack webchat 上花了 5 分钟后,我发现装饰器在当前版本的 babel (v6.2) 中被破坏了。目前唯一的解决办法似乎是降级到 5.8。

他们似乎也将问题跟踪器从 github 移到了 https://phabricator.babeljs.io

我把这一切都写下来了,因为经过几个小时的搜索,我发现当前的文档非常糟糕和缺乏。

你只需要一个转换装饰器插件:http://babeljs.io/docs/plugins/transform-decorators/

这个 Babel 插件对我有用:

https://github.com/loganfsmyth/babel-plugin-transform-decorators-legacy

npm i --save-dev babel-plugin-transform-decorators-legacy

.babelrc

{
  "presets": ["es2015", "stage-0", "react"],
  "plugins": [
    ["transform-decorators-legacy"],
    // ...
  ]
}

Webpack

{
  test: /\.jsx?$/,
  loader: 'babel',
  query: {
    cacheDirectory: true,
    plugins: ['transform-decorators-legacy' ],
    presets: ['es2015', 'stage-0', 'react']
  }
}

React Native

对于 react-native,您必须使用 babel-preset-react-native-stage-0 插件。

npm i --save babel-preset-react-native-stage-0

.babelrc

{
  "presets": ["react-native-stage-0/decorator-support"]
}

请参阅此 question and answer 以获取完整说明。

仅安装 babel-plugin-transform-decorators-legacy 对我不起作用(我有一个使用酶和业力的配置)。原来安装 transform-class-properties: transform-class-properties and also making sure that the legacy plugin is before the transform class plugin as per the docs in transform-decorators-legacy 终于让它对我有用了。

我也没有使用 .babelrc 文件,但将其添加到我的 karma.conf.js 文件对我有用:

babelPreprocessor: {
  options: {
    presets: ['airbnb', 'es2015', 'stage-0', 'react'],
    plugins: ["transform-decorators-legacy", "transform-class-properties"]
  }
}

我也将它添加到我的装载机中:

loaders: [
  {
    test: /\.js$/,
    loader: 'babel',
    exclude: path.resolve(__dirname, 'node_modules'),
    query: {
      presets: ['airbnb', 'es2015', 'stage-0', 'react'],
      plugins: ["transform-decorators-legacy", "transform-class-properties"]
    }
  },

如果您将项目从 Babel 6 升级到 Babel 7,那么您想要安装 @babel/plugin-proposal-decorators

如果你想支持 Babel 5 中使用的遗留装饰器,你需要按如下方式配置你的.babelrc

plugins: [
      ['@babel/plugin-proposal-decorators', { legacy: true }],
      ['@babel/plugin-proposal-class-properties', { loose: true }],
]

确保 @babel/plugin-proposal-decorators 出现在 @babel/plugin-proposal-class-properties 之前,以防您使用后者。