So, you've got a lot of JavaScript code and you've decided to give it some structure - extract & encapsulate modules, set up some dependencies. Most likely you've seen require.js already (or some kind of equivalent) and you love it. It works just fine as long as you're dealing with a homegrown hobbyst Proof-of-Concept fiddling & juggling. But once you're about to release your stuff to the wider audience, you'd like to make sure that it's really efficient (in terms of both response size and quantity) and expected (I keep fingers crossed) hype about your product won't DDoS it accidently ;)

The Flaw

What's the essence of a problem? Vanilla require.js doesn't work well with bundling. Require statement indicates the particular module which is defined by the file or set of files. If you're serious about splitting the actual functionality between several modules, you'll end up with far too many HTTP calls. And as we all know actually reducing the number of HTTP calls is far more important than reducing the communication content's size (within reasonable limits - of course).

Browserify to the rescue

Fortunately, there's Browserify. What does it do?

  • in general, it brings the 'require' statement you know from node.js to your browser applications as well:
var gizmo = require('./gizmo.js');

And what's the benefit?

  1. First, in theory you can run the very same mode (with module dependency statements) in both node.js-based server code and in a browser (obviously, it doesn't work with IO-related code, but these modules are shimmed).

  2. Browserify is able to bundle all the required modules (by a given file) in one big bundle you can reference (and minify, compress, etc.):

	browserify fileWithModReqs.js > reqsModsBundled.js

Justs like that:

	<script src="bundle.js"></script>

The Final Words

  1. Browserify comes as an npm module (if you wonder how to install it).

  2. If you want to learn more, either visit Browserify's home page or try awesome handbook here.

  3. In API, there's a method that will make you able to transform the file content between parsing it by Browsify: b.transform(opts={}, tr)

  4. Obviously, you can put browserify in your grunt's / gulp's processing flow pipeline. How? By using the JavaScript API - try this little snippet:

	var browserify = require('browserify');
	var brw = browserify();
	...

I just wish I knew that project 2 years ago, it would save me significant amount of time...

Share this post