Transform ES2019 to React JSX

I have been given the task of transforming ES2019 compiled React code back to JSX. The client lost their original files and I put my hand up to complete the task. Unfortunately, there are a few hundred files and as I go one by one transforming them, I thought there must be a way to compile them in one go to JSX.

For example a snippet of a file needed to transform may be…

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;

And I want to transform to…

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

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

export default Container;

I know I can transform JSX to JS but how can I reverse this across hundreds of files?

Answer

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

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

babel-js-to-jsx Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *