Babel 6 只有 JSX 转换,没有其他转换

Babel 6 with just JSX transform and no other transforms

我想用babel-plugin-transform-jsx, but no other transforms on some JSX files with some Javascript currently considered at stage 3即候选人

如果这些 JSX 文件包含以下内容,则转译会失败并出现语法错误:

  1. 剩余价差运算符{...x, ...y}
  2. 异步生成器async function * () {}

objective 是为了提高代码在现代浏览器中的调试能力,因为异步生成器的 Babel 转译尤其似乎破坏了 Chrome、Firefox 的开发工具,即断点停止工作,对 this 的引用失败,debugger 调用被跳过,以及许多其他观察到的问题。

除了使用 Babel 生成上述形式的 JSX 之外,似乎别无选择——效果很好;一个理想的解决方案是让 Babel 忽略异步生成器和 rest-spread 运算符(以及它会抛出语法错误的任何其他代码)。

编辑

使用 Victor 建议的插件似乎是正确的解决方案,但 运行 babel-plugin-syntax-async-generators 对此:

class SearchCriteria {
  async * results (authManager) { }
}

导致错误:

Unexpected token, expected "(" (2:10)
  1 | class SearchCriteria {
> 2 |   *async results(authManager) {
    |          ^

Reproducible here,当你添加syntax-async-generators插件时。

Babel 有转换插件和语法插件。转换插件将转换应用于您的代码。语法插件允许 Babel 解析特定类型的 JavaScript 语法,而不是转换它。转换插件将启用相应的语法插件,因此您不必同时指定两者。

所以在你的情况下你需要的是 babel-plugin-transform-jsx transform plugin and two syntax plugins: babel-plugin-syntax-async-generators, babel-plugin-syntax-object-rest-spread.

对应的.babelrc会是:

{
  plugins: ["babel-plugin-transform-jsx", "babel-plugin-syntax-async-generators", "babel-plugin-syntax-object-rest-spread"]
}

最小 package.json:

{
  "name": "babel-jsx",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "build": "babel index.js"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-syntax-async-generators": "^6.13.0",
    "babel-plugin-syntax-object-rest-spread": "^6.13.0",
    "babel-plugin-transform-jsx": "^2.0.0",
    "react": "^16.4.1"
  }
}

如果您在 index.js 中有 JavaScript 这样的代码:

import React from 'react'

const MyComp = <div>Hello</div>;

async function* myfunc() {
  const array = [1, 2, 3];
  console.log(...array);
}

和运行命令:

yarn

yarn build

那么输出将是:

$ babel index.js
import React from 'react';

const MyComp = {
  elementName: 'div',
  attributes: {},
  children: ['Hello']
};

async function* myfunc() {
  const array = [1, 2, 3];
  console.log(...array);
}