【问题标题】:Babel: use subset of stage-x preset plugins?Babel:使用 stage-x 预设插件的子集?
【发布时间】:2016-04-20 00:58:20
【问题描述】:

如何使用 stage-x“预设”中的两个特定 Babel 插件,而不必使用整个预设?

具体来说,我想在我的 ES6 类中使用 transform-class-properties 和 transform-decorators,这两个类目前都建议用于 ES7 和 stage-1 预设的一部分。

【问题讨论】:

  • 注意,如果你需要 Babel 6 的装饰器,你可能需要babel-plugin-transform-decorators-legacy,而不是babel-plugin-transform-decorators
  • 您应该将您的更新发布为答案并将其标记为已接受。它比我现有的答案要详细得多
  • 感谢@RGraham 的反馈——完成!

标签: babeljs


【解决方案1】:

presets 只是较小的plugins 的集合,因此您可以使用该选项来提取您需要的转换:

.babelrc(或配置)

{
  "presets": ["es2015"],
  "plugins": ["transform-class-properties", "transform-decorators"]
}

会给你所有的 ES2015 + 类属性 + 装饰器

【讨论】:

  • 最好列出 transform- 插件而不是 syntax- 插件。您的建议将使它们解析,但不会转换它们。
  • 谁能告诉我 transform-class-properties 是做什么的?我宁愿不为此创建一个新问题,因为我认为这不值得一个大答案 - 但 NPM 和 github 页面并没有说清楚。
【解决方案2】:

@RGraham 的回答很有帮助——还想分享更多细节...

我正在使用 gulp,所以首先我必须从 gulp-babel 5.x 升级到 6.x: npm install --save-dev babel/gulp-babel

然后我需要安装 ES2015 预设和我想使用的两个插件(+ 反应预设,因为我使用的是 ReactJS):

  npm install --save-dev babel-preset-es2015
  npm install --save-dev babel-preset-react
  npm install --save-dev babel-plugin-transform-class-properties 
  npm install --save-dev babel-plugin-transform-decorators

最后,我将以下配置传递给 Babel(您也可以在 .babelrc 文件中指定):

{
  presets: ['es2015', 'react'],
  plugins: [
    ["transform-class-properties"],
    ["transform-decorators"]
  ]
}

您的 JavaScript linter 会抱怨 ES7 语法。 This blog post 描述了解决方案:修改 lintjs 以使用 Babel 作为 JavaScript 解析器。然后在你的.eslintrc 文件中设置"parser": "babel-eslint"

npm install --save-dev babel-eslint

最后,对于任何其他 ReactJS 人员,请确保修改组件的构造函数以包含道具和上下文参数,否则您可能会收到类似 TypeError: Cannot read property 'xxx' of undefined 的运行时错误。这是一个例子:

/**
   * ES6 constructor method (takes the place of the old React componentWillMount() method).
   * 
   * @param  {Object} props   See https://facebook.github.io/react/docs/reusable-components.html
   * @param  {Object} context See https://facebook.github.io/react/docs/context.html
   */
  constructor(props, context) {
    super(props, context);
    log.debug(`Creating ${this.constructor.name} instance`, props, context);
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-12
    • 2016-09-12
    • 2020-10-16
    • 2018-02-11
    • 2019-03-18
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    相关资源
    最近更新 更多