Export a Global to the Window Object with Browserify

Browserify is a pretty slick tool that lets developers use node.js-style requires in their browser-deployed javascript. This gives significant advantages such as importing libraries from the thousands available on npm or being able to run unit tests headlessly in node.

Using a module system like Browserify and require is one of the many techniques that help javascript developers craft modular code that doesn’t accidentally leak variables into the global scope. But sometimes the whole purpose of a library is to do exactly that: export a namespaced set of objects that other scripts can use. If all of the developer’s code is hidden inside a closure and accessed internally through require, how can other third party scripts use the library?

But there’s no reason a developer couldn’t just export the required modules manually. All she has to do is include an exports.js script that sticks requireed objects onto the window object. Putting them all in an exports.js file sends a clear signal that the referenced modules are meant for public consumption.

Something like the following is usually sufficient.

acme_corp/src/exports.js
1
2
3
4
5
6
7
8
9
10
11
12
// Grab an existing namespace object, or create a blank object
// if it doesn't exist
var Acme = window.Acme || {};

// Stick on the modules that need to be exported.
// You only need to require the top-level modules, browserify
// will walk the dependency graph and load everything correctly
Acme.RoadRunner = require('./roadrunner');
Acme.Coyote = require('./coyote');

// Replace/Create the global namespace
window.Acme = Acme;

Now third-party or other external scripts will be able to access the exported modules right off the window global.

index.html
1
2
3
4
5
<script type='text/javascript' src='/js/acme.min.js'></script>
<script type='text/javascript'>
var wiley = new Acme.Coyote();
wiley.chase(new Acme.RoadRunner());
</script>