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
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!
From there, we can create our
package.json file, starting with (dev)dependencies:
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.
Our second script is the watcher. It works exactly the same except it uses
watchify instead of
Last but not least, we put them in our
Done! At this point, the basic
index.html page can safely link to