Created
August 20, 2011 22:51
-
-
Save addyosmani/1159780 to your computer and use it in GitHub Desktop.
commonjs-module-boilerplates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Courtesy of Sitepen | |
*/ | |
/* | |
First, let’s look at very lightweight, but powerful boilerplate, an adapter that will let you write a module for both AMD and CommonJS standard module systems, using AMD style dependency declarations. This combination allows us to create modules that can be used both in browser and server environments: | |
*/ | |
(function(define){ | |
define(["dep1", "dep2"], // a list of our dependencies | |
function(dep1, dep2){ // the arguments match up with our dependencies | |
// the contents of our module | |
... | |
// what we return from our module | |
return { | |
someExportedFunction: function(){...}, | |
... | |
} | |
}); | |
})(typeof define=="function"?define:function(factory){module.exports=factory.apply(this, deps.map(require));}); | |
/* | |
We can also achieve compatibility with AMD and standard CommonJS by putting boilerplate around the standard CommonJS module format: | |
*/ | |
(function(define){ | |
define(function(require,exports){ | |
// module contents | |
var dep1 = require("dep1"); | |
exports.someExportedFunction = function(){...}; | |
... | |
}); | |
})(typeof define=="function"?define:function(factory){factory(require,exports)}); | |
/* | |
You can even combine styles, for example you could use CommonJS style require calls with the AMD style of using a return to export functionality: | |
*/ | |
(function(define){ | |
define(function(require){ | |
return { | |
someMethod: function(){ | |
... | |
} | |
} | |
}); | |
})(typeof define=="function"?define:function(factory){module.exports = factory(require)}); | |
/* | |
Next we will look at the boilerplate for creating dependency free modules that can run on all four systems: | |
Remember that you can’t declare any dependencies with this last boilerplate, because it is designed to work as a plain script without the help of any module loader (that would resolve the dependencies). But, if you have a dependency free module, this gives you maximum portability. | |
*/ | |
(function(name, factory){ | |
typeof require == "undefined" ? | |
(typeof dojo != "undefined" && dojo.provide(name)) & | |
// direct script | |
factory(this[name] = {}) : | |
typeof exports == "undefined" ? | |
// browser transport/C loader or RequireJS | |
define(name, ["exports"], factory) : | |
// CommonJS environment | |
factory(exports); | |
})("module-name", function(exports){ | |
// actual module contents following CommonJS format (assigning values/function as properties of exports) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment