This post attempts to compare RequireJS/AMD with Browserify/CommonJS as packaging and modularization approaches for modern web applications.
Modules are built according to the CommonJS pattern and work in both NodeJS and the browser. They export their dependencies through the module.exports
key.
var fs = require('fs');
var angular = require('angular'),
otherservice = require('./otherservice');
var ngModule = angular.module('my.module');
var template = fs.readFileSync(__dirname + '/template.html', 'utf-8');
ngModule.directive('myDirective', function() {
return {
template: template
};
});
module.exports = ngModule;
Modules are built according to the asynchronous module definition pattern and wrapped in a require
/define
callback that returns the module export.
define([ 'angular', './otherservice', 'text!./template.html' ], function(angular, otherservice, template) {
var ngModule = angular.module('my.module');
ngModule.directive('myDirective', function() {
return {
template: template
};
});
return ngModule;
});
Optionally you can use a CommonJS like require('dependency')
syntactic sugar.
define(['require', 'angular', './otherservice', 'text!./template.html' ], function(require) {
var angular = require('angular'),
otherservice = require('./otherservice');
var ngModule = angular.module('my.module');
var template = require('text!./template.html');
ngModule.directive('myDirective', function() {
return {
template: template
};
});
return ngModule;
});
The following table compares multiple aspects of each approach.
aspect | RequireJS + AMD | Browserify + CommonJS |
---|---|---|
loading | async (default), sync (after minification) | sync (after processing) |
preprocessing | optional | mandatory (creates browser compatible file) |
dependency declaration | via require#config |
package.json |
transitive external dependencies | must be declared in global config | automatically managed |
project packaging | n/a, user defined | npm |
module definition | AMD, define([ ... ], function() { } |
CommonJS, module.exports = ... |
async loading | yes | no |
minifies to | single / multiple files, AMD/UMD | single / multiple files, require stub (default), global object, UMD |
resource inlining / preprocessing | loader plug-ins, e.g. text |
transforms, e.g. brfs |