Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created September 6, 2011 18:10
Show Gist options
  • Save ryanflorence/1198466 to your computer and use it in GitHub Desktop.
Save ryanflorence/1198466 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();
@millermedeiros
Copy link

including dependencies: https://github.com/millermedeiros/crossroads.js/blob/a03c8ef5d5/dist/crossroads.js#L339-357

note that my code isn't flexible, I'm listing signals as a dependency on the regular browser version since I know that signals is the only dependency, could be abstracted tho..

@jrburke
Copy link

jrburke commented Oct 4, 2011

I'm playing around with a format here: https://gist.github.com/1262861

It puts most of the nasty adapter stuff at the bottom, so readers of the code can focus first on the module's capabilities and not the registration boilerplate. It is a bit opinionated though.

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