Skip to content

Instantly share code, notes, and snippets.

@junosuarez
Created November 2, 2012 18:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junosuarez/4003398 to your computer and use it in GitHub Desktop.
Save junosuarez/4003398 to your computer and use it in GitHub Desktop.
Micro-UMD format
/* The problem: writing boiler plate sucks.
* Writing modules that aren't portable between Node.js and AMD also sucks.
* Writing monolithic code (and not using modules) is perhaps worst of all, and
* should be punishable by death.
*
* UMD stands for Universal Module Definition (https://github.com/umdjs/umd)
* and provides boiler plate to create modules that work anywhere - but it's
* bulky.
*
* Here's a minimal implementation which makes certain assumptions about
* common node and AMD environments. It gets out of your way, so you can focus
* on writing real code^TM.
*/
// Full version
(this.define || function(x, m) { m(require, module); })(['require', 'module'],
function (require, module) {
// module code here
module.exports = {};
});
// Annotated
// Get the 'define' function
(
this.define // if it is declared, assume it's AMD define
|| // otherwise, we have to stub it out for Node's require
function(x, m) { // we don't need the first variable- only AMD define uses it
// m is the function that defines the module. AMD calls it a
// factory function
m(require, module); // Invoke the factory, passing through Node's require
// and module object
}
) // Now we have a define function, let's invoke it immediately
(['require', 'module'], // tell AMD define which modules we need.
// We use the special 'require' and 'module' handlers
function (require, module) { // Create a module factory function
// module code here
module.exports = {}; // Use module.exports like we normally would
}); // close the factory function and the invocation paren
// Shorter version for modules with no dependencies
(this.define || function(x, m) { m(module); })(['module'],
function (module) {
// module code here
module.exports = {};
});
// In a tweet :)
(this.define||function(x,m){m(exports)})(['exports'],
function(exports){
exports=function(){return 'OHAI @jrburke!'}
})
@junosuarez
Copy link
Author

Disclaimer, @jrburke pointed out to me in a tweet that this format can't be used with the current r.js optimizer for anonymous modules. YMMV.

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