Skip to content

Instantly share code, notes, and snippets.

@nielswind
Forked from ryanflorence/universal-module.js
Created February 22, 2012 19:01
Show Gist options
  • Save nielswind/1886666 to your computer and use it in GitHub Desktop.
Save nielswind/1886666 to your computer and use it in GitHub Desktop.
Universal JavaScript Module, supports AMD (RequireJS), Node.js, and the browser.
(function (name, definition){
if (typeof define === 'function'){ // AMD
define(definition);
} else if (typeof module !== 'undefined' && module.exports) { // Node.js
module.exports = definition();
} else { // Browser
var theModule = definition(), global = this, old = global[name];
theModule.noConflict = function () {
global[name] = old;
return theModule;
};
global[name] = theModule;
}
})('myModule', function () {
// return the module's API
return {};
});
// AMD
require(['path/to/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