Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tool to transpile from js to jsx

I'm curious if any of the transpiling tools will convert from plain JS to JSX. Babel will transpile JSX to JS, but as far as I know it cannot go back to JSX.

From the example:

var Nav;
// Input (JSX):
var app = <Nav color="blue" />;
// Output (JS):
var app = React.createElement(Nav, {color:"blue"});

Are there tools that go the other direction:

var Nav;
// Input (JS):
var app = React.createElement(Nav, {color:"blue"});
// Output (JSX):
var app = <Nav color="blue" />;

Thanks!

like image 751
thomas Avatar asked Dec 09 '15 22:12

thomas


People also ask

How do I convert React JS to JSX?

The converted code will look like this now: import React from "react"; import ReactDOM from "react-dom"; const App = () => { return ( React. createElement("p", null, "This is first JSX Element!"); React. createElement("p", null, "This is another JSX Element"); ); }; const rootElement = document.

Can we use JS and JSX together?

You can put any valid JavaScript expression inside the curly braces in JSX. For example, 2 + 2 , user.firstName , or formatName(user) are all valid JavaScript expressions. In the example below, we embed the result of calling a JavaScript function, formatName(user) , into an <h1> element.

What tool do we use to translate JSX into standard JavaScript?

Browsers don't understand JSX out of the box, so most React users rely on a compiler like Babel or TypeScript to transform JSX code into regular JavaScript. Many preconfigured toolkits like Create React App or Next. js also include a JSX transform under the hood.


1 Answers

I haven't tried it myself, but there is apparently now a babel plugin to do exactly what you ask.

babel-js-to-jsx

https://github.com/JoeStanton/babel-js-to-jsx

Per the documentation:

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: ["js-to-jsx", "syntax-jsx"],
}).code

Or from the command line for composition with other tools:

npm install babel-plugin-js-to-jsx
cat example.ls | lsc -cb --no-header | js-to-jsx | esformatter -c format.json
like image 116
nextgentech Avatar answered Oct 31 '22 10:10

nextgentech