I recently wanted to create a tiny tiny React component outside of any React project I am currently working on. Something small, to be tested in the browser, just as an experiment. It actually took me some time to figure out the best way to work on this, so I thought it might be worth a short blog post in case you are in such a need too.
And because I wanted to import React as a dependency inside my component, and not rely on global variables and import React as a script in the browser, I needed a way to make import/require work in the browser. To do so, there is Browserify.
Now, using them both could be tricky if it was not for Babelify. It is a Babel plugin doing both ES6 to 5 compilation and Browserify magic. To be entirely honest with you right now, I am not entirely sure what I’m saying. But that’s basically how it works.
Last but not least, I came across Watchify, a watch mode for Browserify builds. This extra tool allowed me to have a watcher running to make Babelify recompile the dist file every time there is a change. Handy!
Now, we only need to create a pair of npm scripts to make our life easier and save us from typing some long commands again and again. The first script we need is a build task. It runs browserify binary on our main file, compile it with babelify binary, then output in a new file.
"watch": "watchify src/browser.js -t babelify -o dist/index.js"