As of 2023 if you are using babel to transform jsx
to js
, this is what you will need to do:
Install Packages
Install the following globally on your machine:
npm install -g @babel/cli
npm install -g @babel/core
npm install -g @babel/preset-react
or install the following as a project dependency (my personal preference):
npm install --save-dev @babel/cli
npm install --save-dev @babel/core
npm install --save-dev @babel/preset-react
Create Configuration File
Create a .babelrc
config file at the root of your project with the following setting as a bare minimum:
{
"presets": ["@babel/preset-react"]
}
You should review the babel docs if you have a more complicated use case and determine what additional settings you may need to add. You can find the settings for compiling jsx
to js
on the @babel/preset-react page.
Compile
You can compile any jsx
file into js
by running the following command in your terminal:
npx babel [jsx-file-here.jsx] -d [output-directory]
If your jsx
file imports anything please keep the following in mind:
- This will not import any imported code. You will need to also compile any files that are imported. You can then use your code as a browser module: see next 2 points.
- JS imports are widely supported now (see also) but you will need to add
type="module"
to the script tag in your HTML.
- Remember you must include the file extension
.js
in your import statements still! No browser will intuptret import Foo from './bar' as import Foo from './bar.js
.
- If you do not want to do the previous you can use something like rollup.js to bundle all the files into a single script.
babel
command? Also, thereact
preset is probably a better thing to use in the.babelrc
.