Skip to content

Instantly share code, notes, and snippets.

@unscriptable
Created November 20, 2012 15:11
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save unscriptable/4118495 to your computer and use it in GitHub Desktop.
Save unscriptable/4118495 to your computer and use it in GitHub Desktop.
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
Copy link

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