Skip to content

Instantly share code, notes, and snippets.

@ifandelse
Last active December 11, 2015 14:59
Show Gist options
  • Save ifandelse/4617996 to your computer and use it in GitHub Desktop.
Save ifandelse/4617996 to your computer and use it in GitHub Desktop.
UMD boilerplate to handle AMD, Commonjs, and standard browser js
// Example UMD wrapper for a module that takes dependencies on underscore and postal.js
(function ( root, factory ) {
if ( typeof module === "object" && module.exports ) {
// Node, or CommonJS-Like environments
// Intentionally returning a factory method
module.exports = function( _, postal ) {
return factory( _, postal );
}
} else if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( ["underscore", "postal"], function ( _, postal ) {
return factory( _, postal, root );
} );
} else {
// Browser globals
factory( root._, root.postal, root );
}
}( typeof global !== "undefined" ? global : this.window || this.global, function ( _, postal, global, undefined ) {
// module code here....
});
@unscriptable
Copy link

Yah, I almost slapped my own forehead when I realized this.window finds window when this == window or document == window. Kinda neat.

It's still unclear to me why you need to export a factory for node in order to support singletons. Maybe I just haven't played with node enough to know why singletons can be a problem. Is this why? Interesting. So how is that factory called? How do you get the "true singletons" into that factory? (Sorry if I'm being too curious for you. :) )

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