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....
});
@ifandelse
Copy link
Author

@unscriptable - seriously, man, you are my code hero. First, to answer your question: I'm opting for the factory in node because I often have situations where I want the same instance of a dependency to be passed in to multiple factories. postal is good example, as the add-ons for it need to target the same instance. It's one of the nice by-nature-of-design aspects of AMD, IMO - singletons are easy. I wish node had that capability built in. If you think of something I'm missing here, let me know.

I like your idea a lot - makes tons of sense. Not sure why this.window didn't occur to me! smacks forehead. I updated the gist to reflect your input....

@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