Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform JSX to JS using babel

I'm new to babel and I'm trying to convert my main.jsx file to main.js. I installed the following babel plugin.

npm install --save-dev babel-plugin-transform-react-jsx

Created a file called .babelrc in the application root directory.

{
   "plugins": ["transform-react-jsx"]
}

My app is using the express server, so on running node app.js I was expecting the babel to transform main.jsx to main.js but nothing happens. Can any one point out what I'm doing wrong ?

like image 671
iJade Avatar asked Mar 30 '17 07:03

iJade


People also ask

Does Babel convert JSX to JS?

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.

How is JSX converted to JS?

So to convert it to browser understandable JavaScript code, we use a tool like Babel which is a JavaScript compiler/transpiler. You can set up your own babel configuration using Webpack as I show in this article. Or you can use create-react-app which internally uses Babel for the JSX to JavaScript conversion.

Does JSX use Babel?

JSX should not be implemented directly by browsers, but instead requires a compiler to transform it into ECMAScript. This is where Babel comes in. Babel acts as this compiler allowing us to leverage all the benefits of JSX while building React components.


1 Answers

if you are only using babel to transform jsx to js, this is what you need :

installation

  • install babel-cli as global (optional) sudo npm install -g babel-cli
  • install babel-preset-es2015 (optional. if your code using es6 standard) npm install babel-preset-es2015
  • install babel-preset-react (required)

configuration

in your root of project, add this file .babelrc and write this to it

{
  "presets": ["es2015", "react"]
}

or

{
  "presets": ["react"]
}

run

babel source_dir -d target_dir
like image 63
yussan Avatar answered Oct 02 '22 12:10

yussan