Converting JSX to JS on the command line

Last modified date

Comments: 0

Yesterday I was starting a small, very stand-alone project that required a pretty dynamic interface. I decided to put together the components using ReactJS but as it was essentially just one JSX file that I had I didn’t want to have to set up a gulp file, babelrc file, and whatever new-fangled build process the young kids are in to these days.

I thought about not using JSX syntax, but I think it adds a level of readability to the code and will make it easier for myself and others to maintain longer term, and besides which, I had already writing the JSX part and didn’t want to redo the work. Thankfully, though, it’s really easy to use Babel from the command line to do the conversion,.

First, install the required npm modules (I did this globally so that I could use it anywhere on the cli, not just in the specific project):

npm install --global babel-cli babel-plugin-transform-react-jsx babel-plugin-transform-es2015-arrow-functions

I included the es2015 arrow functions plugins so that I could do things like () => this.handleClick(this.props.val)

Once that was installed I could simply set babel to watch my JSX folder and compile automatically when I changed anything in there:

babel --plugins transform-react-jsx,transform-es2015-arrow-functions jsx/ --watch --out-dir .

Obviously you’d change the --out-dir to wherever you’d want to output the .js file.

So now when I change a file in my jsx folder, such as components.jsx, it will create the equivalently name components.js file, correct transpiled and converted from JSX (and ES2015 arrow functions) to good ol’ javascript with ES5 bind methods.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.