将 ES2019 转换为 React JSX

Dar*_*ren 10 javascript reactjs

我的任务是将 ES2019 编译的 React 代码转换回 JSX。客户丢失了他们的原始文件,我举手完成了任务。不幸的是,有几百个文件,当我一个一个地转换它们时,我认为必须有一种方法可以一次编译它们到 JSX。

例如,需要转换的文件片段可能是...

import _extends from "@babel/runtime/helpers/extends";
import React from 'react';
import { Item } from './Item';

const Container = props => {
  return /*#__PURE__*/React.createElement("div", _extends({}, props, {
    component: props.component || Item,
  }));
};

export default Container;
Run Code Online (Sandbox Code Playgroud)

我想转变为...

import React from 'react';
import { Item } from './Item';

const Container = (props) => {
  return <div component={props.component || Item} />;
};

export default Container;
Run Code Online (Sandbox Code Playgroud)

我知道我可以将 JSX 转换为 JS,但如何在数百个文件中反转它?

Hit*_*mar 6

There is apparently a babel plugin to do exactly what you ask. -> babel-js-to-jsx

Babel 6 plugin to convert from desugared React.DOM CallExpressions -> the equivalent JSX. Currently used to migrate to ES6+ from other compile to JS languages.

It can be used as a plugin:

require("babel-core").transform(code, {
  plugins: ["babel-transform-js-to-jsx", "syntax-jsx"],
}).code

Run Code Online (Sandbox Code Playgroud)

Or from the command line for composition with other tools:

npm install babel-transform-js-to-jsx
cat example.ls | lsc -cb --no-header | js-to-jsx | esformatter -c format.json
Run Code Online (Sandbox Code Playgroud)

babel-js-to-jsx Documentation