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!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With