Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple AMD/node boilerplate. These aren't quite "normal" AMD and aren't "pure" CJS, but work in AMD loaders and node-like environments (like RingoJS).
// Typical AMD factory that returns a value, but uses an r-value (sync) require(),
// rather than a long, awkward dependency list.
// You cannot use module.exports or exports to declare the module:
(function (define){
define(function (require) {
"use strict";
var mod = require('pkb/modA');
return {
delegate: function () {}
};
});
}(
typeof define == 'function' && define.amd
? define
: function (factory) { module.exports = factory(require); }
));
// More CJS-like factory that uses module.exports to declare a value.
// You cannot declare the module by returning a value:
(function (define){
define(function (require, exports, module) {
"use strict";
var mod = require('pkb/modA');
module.exports = {
delegate: function () {}
};
});
}(
typeof define == 'function' && define.amd
? define
: function (factory) { factory(require, exports, module); }
));
// As long as modules are never declared as falsey values, this
// flavor will support typical AMD factories and CJS-like factories:
// HT to @bryanforbes
(function (define){
define(function (require, exports, module) {
"use strict";
var mod = require('pkb/modA');
module.exports = {
delegate: function () {}
};
// could also return here instead of using module.exports
});
}(
typeof define == 'function' && define.amd
? define
: function (factory) { module.exports = factory(require, exports, module) || exports; }
));
@anodynos

This comment has been minimized.

anodynos commented Oct 29, 2013

These are quite usefull boilerplates, but one should mind the extra effort the AMD loader has to go through while loading in the browser: its parsing the code of each module, trying to find all require('dep') calls and pre-load 'em BEFORE it can execute these seamingly synchronous require calls.

The UMD approach in uRequire is different in this aspect: it analyzes you code at build time, adding all require('dep') calls in the dependency array i.e define(['dep1', 'dep2'], function(dep1, dep2){}) eliminating the browser AMD loader from parsing/analysing the JS. The UMD used in uRequire is inspired by https://github.com/umdjs/umd

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment