CommonJS For The Browser
A CommonJS preprocessor that builds you CommonJS style app into code the browser can use.
Install
$ npm install common.js
Usage
Step 1: Write your JavaScript
foo.js
module.exports = function() {
console.log('foo');
};
bar.js
var foo = require('foo');
exports.doTheThing = function() {
foo();
};
Step 2: Build you code using commonjs-preprocessor
$ commonjs --src ./path/to/javascripts --dest ./path/to/js --client
Step 3: Include the modules into your app and use them
<script src="js/common.js"></script>
<script src="js/foo.js"></script>
<script src="js/bar.js"></script>
<script>
var bar = require('bar');
bar.doTheThing();
</script>
Command-line Usage
Usage: commonjs [options]
Options:
-h, --help output usage information
-V, --version output the version number
-s, --src <src> Source directory
-d, --dest <dest> Destination directory
--client [client] Output a common.js client script
-v, --verbose Verbose output
-q, --quiet Quite running mode (no output)
How Does It Work Internally
The common.js preprocessor works by wrapping each of your JavaScript files in an extra function call which defines all the necessary bits for a CommonJS module (such as the module
and exports
variables). A compiled module looks something like this (except this has been cleaned up for reading):
;
require._modules["/bar.js"] = (function () {
var __filename = "/bar.js";
var __dirname = "/";
var module = {
loaded: false,
exports: {},
filename: __filename,
dirname: __dirname,
require: null,
call: function () {
var require = module.require;
module.loaded = true;
module.call = function () {};
__module__();
},
parent: null,
children: []
};
var exports = module.exports;
/* == Begin source for module /bar.js == */
var __module__ = function () {
var foo = require('./dir/foo');
exports.doTheThing = function () {
foo();
};
}; /* == End source for module /bar.js == */
module.require = require._bind(module);
return module;
}());;
Once your modules are compiled, you add in the very tiny common.js
client library which defines the require
function and contains the rules for resolving modules. And that's it.
It should be noted that this is a 100% synchronous process, which means any module you intend to require has to loaded in the DOM before the require
call is made.