-
-
Save millermedeiros/1251668 to your computer and use it in GitHub Desktop.
Universal JavaScript Module, supports AMD (RequireJS), Node.js, and the browser.
This file contains 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
(function(def){ | |
def('myModule', ['someDependency', 'somethingElse'], function(someDependency, somethingElse){ | |
//return the module's API | |
return {}; | |
}); | |
}( | |
// wrapper to run code everywhere | |
typeof define === 'function' && define.amd? | |
//AMD | |
function(name, deps, factory){ | |
define(deps, factory); //registering as an unnamed module, more flexible and match CommonJS | |
} : | |
(typeof require === 'function' && typeof module !== 'undefined' && module.exports ? | |
//CommonJS | |
function(deps, factory){ | |
module.exports = factory.apply(this, deps.map(require)); | |
} : | |
//Browser (regular script tag) | |
function(name, deps, factory){ | |
var d, i = 0, global = this, old = global[name], mod; | |
while(d = deps[i]){ | |
deps[i++] = this[d]; | |
} | |
global[name] = mod = factory.apply(global, deps); | |
mod.noConflict = function(){ | |
global[name] = old; | |
return mod; | |
}; | |
} | |
) | |
)); |
This file contains 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
// AMD | |
require(['myModule'], function (myModule){ | |
// use myModule here | |
}); | |
// Node.js | |
var myModule = require('myModule'); | |
// Global | |
myModule | |
// if myModule is already defined, `noConflict` gives it back | |
var myNonConflictingModule = myModule.noConflict(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in case someone reaches this gist, I just published a new post explaining why AMD rocks: http://blog.millermedeiros.com/2011/09/amd-is-better-for-the-web-than-commonjs-modules/