Skip to content

Instantly share code, notes, and snippets.

@accerqueira
Created August 12, 2014 20:42
Show Gist options
  • Save accerqueira/90d7a7b11083dd73fe3d to your computer and use it in GitHub Desktop.
Save accerqueira/90d7a7b11083dd73fe3d to your computer and use it in GitHub Desktop.
javascript umd
(function (name, dependencies, factory, context) {
var args = Array.prototype.slice.call(arguments);
var argsTypes = ['string', 'object', 'function', 'object'];
var argsDefaults = ['', [], undefined, {}];
for (var i = 0; i < argsTypes.length; i++) {
if (typeof args[i] !== argsTypes[i]) {
args.splice(i, 0, argsDefaults[i])
}
}
name = args[0], dependencies = args[1], factory = args[2], context = args[3];
if (typeof define === 'function' && define.amd) {
define(name, dependencies, factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory.apply(context, dependencies.map(function(name) { return require(name); }));
} else {
var mod = factory.apply(context, dependencies.map(function(name) { return context[name]; }));
if (name) context[name] = mod;
}
})('mymodule', ['dependency1', 'dependency2'], function(dependency1, dependency2) {
var mymodule = {};
return mymodule;
}, this);
@accerqueira
Copy link
Author

  • name, dependencies and context are optional
  • dependencies are loaded amd-style or commonjs-style accordingly

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