Hints of RequireJS in Your Browserify Project

- - | Comments

Now that it’s 2014 and I’ve read that blog post about everyone being scared of moving to 1.0.0, I’m excited to announce a JavaScript project of mine that will help RequireJS users feel a little more comfortable with the browserify ecosystem.

On demand async loading of modules in the browser

Promethify is a browserify transform that allows for the async module loading that RequireJS solves for out of the box. It’s intended to be used to only load what you need.

It allows you to specify what modules are needed to be loaded dyanmically just like RequireJS. Pass as it’s first parameter, an array of dependencies instead of strings, and boom, everything else just works.

You can use it to write code like this in browserify:

1
2
3
4
5
6
7
8
9
//main.js
var $ = require('jquery');

$('.buy-product').click(function(){
  require(['/shopping-cart'], function(shoppingCart) {
    // only downloaded shopping cart code including jqueryui when necessary
    shoppingCart.open();
  });
});
1
2
3
4
5
6
7
8
9
//shopping-cart.js
var $ = require('jquery');
require('jqueryui');

module.exports = {
  open: function(){
    // open modal with jquery ui
  }
}

There are a few exising alternative approaches out there to achieve lazy loading with browserify, but they all have the same large con for me. They all require significant build/configuration changes for each module that needs to be asynchronously loaded.

The few goals for this project in relation to the other solutions were to

  1. Have RequireJS-like simplicity in how to define what modules are loaded asynchronously. Just add it to the dependency array, and all of the hard work is taken care of for you.
  2. Have a completely opaque mechanism for fetching and generating the JavaScript file for the module. I don’t want a user to think about jQuery.getScript.
  3. The interface should be a regular browserify transform that takes configuration from package.json so this could be used from the browserify CLI as well as a custom bundling script.

I am hopeful that this will open up a whole new world of possibilities for browserify. As a huge RequireJS fan, this is something that I’ve sorely missed as I’ve used browserify on larger applications.

Please let me know your thoughts in the comments or on twitter. I’d love to hear why this is a great/horrible idea, or how I can make it better.

Comments