Building Libraries With Browserify
I started putting together many of my “go-to” code snippets this week. It’s something I have tried to start multiple times but I was never really satisfied with the process of compiling the snippets into their more ubiquitous form, the ‘common.js’ file.
In my utils repo, I’m trying out a pattern using
browserify transforms that might work. I can keep the individual snippets
separate, letting node’s
require figure out dependencies, and still have a simple build process
that gives me the
utils.js file I need–per project.
It works like this:
- Write a bunch of simple methods or one-liners that you use all the time.
- Write a transform like my
Then call browserify from the command line, passing the names of files to include to the transform.
- Then call
node build.jsfrom the command line, optionally passing the names of files to include
node build.js ncurry compose output=utils.js
The source file,
./src/utils.js, is just an empty file. The transform reads the list of method/file names
_subargs_, parameters, and creates a list of
global.<name> = require(<name>); strings, and pipes it to
the destination file. In this case, the transform will generate a file with
and any of their dependencies but only the two named methods will get exposed as globals.
Dependencies can even include other npm modules!
Comments, suggestions, and pull requests welcome.
The original transform left a lot of boilerplate in the bundle file because I was using the browserify api incorrectly. This new version works much better and reduces the wrapper code browserify adds. I also think the command line invocation of build is more convenient. I’m much happier with this version and I will probably work on making the build file more generic so it can be broken out as its own module.