Recently I hopped over to the React blog and in their latest article, they announced they were deprecating react-tools. This had been a great tool for me, making use of it via gulp-react which has served me well to transform my JSX into plain JS. In React’s post though, they mentioned about migrating to Babel which supports converting JSX to vanilla JS. Babel’s website has some documentation on using Babel with various build systems. In my case, I was using Gulp with Browserify. For a complete working example head on over to Github. This sample runs a Spark web application with embedded Jetty server.
React ES6 Modules
Traditionally, I would write modules in the following way and then use gulp-react to transform the JSX into plain JS. Then pass the result through Browserify to bundle up all of my components and scripts.
Moving to ES6 module syntax and using Babel, there’s no longer a need for gulp-react. This is the same module written in ES6. The Babel team has written the Babelify transformer for Browserify, so in a single task, this code is transformed to plain JS and bundled up with all my other scripts. You’ll need to keep in mind that React only supports ES6 classes as of version 0.13 which was recently released.
Using Babel with Browserify
Now that we have React components written in ES6 module format, we can use Babel with Browserify. Here is the pertinent task from the Gulp build file I use in the sample project mentioned above. Be sure to look at the sample project for the full Gulp file. This task externalizes NPM managed dependencies so they’re not included in the bundle. Another task takes care of bundling NPM dependencies into a vendor bundle which gets loaded ahead of this resulting scripts bundle.
Overall, this wasn’t too difficult of an undertaking. The longest part was getting the Gulp build to work the way I wanted it to. Namely generating separate bundles for vendor scripts and app scripts, along with a few extra build steps I added for uglify, reving and injecting scripts into the index.html file. I had originally started the sample project using a Broccoli build, but couldn’t get the Browserify plugin to work the way I wanted, so I switched to Gulp which I had more experience using.