install
The CommonJS module syntax is one of the most widely accepted conventions in the JavaScript ecosystem. Everyone seems to agree that require
and exports
are a reasonable way of expressing module dependencies and interfaces, and the tools for managing modular code are getting better all the time.
Much less of a consensus has developed around the best way to deliver CommonJS modules to a web browser, where the synchronous semantics of require
pose a non-trivial implementation challenge. This module loader contributes to that confusion, yet also demonstrates that an amply-featured module loader need not stretch into the hundreds or thousands of lines.
Installation
From NPM:
npm install install
From GitHub:
cd path/to/node_modules
git clone git://github.com/benjamn/install.git
cd install
npm install .
Usage
The first step is to create an install
function by calling the
makeInstaller
method. Note that all of the options described below are
optional:
var install = require("install").makeInstaller({
extensions: [".js", ".json"],
fallback,
browser,
mainFields: ["browser", "main"],
});
The second step is to install some modules by passing a nested tree of
objects and functions to the install
function:
var require = install({
"main.js"(require, exports, module) {
var assert = require("assert");
assert.strictEqual(
require("package").name,
"/node_modules/package/entry.js"
);
exports.name = module.id;
},
node_modules: {
package: {
"package.json"(require, exports, module) {
exports.name = "package";
exports.version = "0.1.0";
exports.main = "entry.js";
},
"entry.js"(require, exports, module) {
exports.name = module.id;
}
}
}
});
Note that the install
function merely installs modules without
evaluating them, so the third and final step is to require
any entry
point modules that you wish to evaluate:
console.log(require("./main").name);
This is the "root" require
function returned by the install
function. If you're using the install
package in a CommonJS environment
like Node, be careful that you don't overwrite the require
function
provided by that system.
If you need to change the behavior of the module
object that each module
function receives as its third parameter, the shared Module
constructor
is exposed as a property of the install
function returned by the
makeInstaller
factory:
var install = makeInstaller(options);
var proto = install.Module.prototype;
proto.require = wrapWithLogging(proto.require);
proto.newMethod = function () {...};
Many more examples of how to use the install
package can be found in the
tests.