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();
@arian
Copy link

arian commented Sep 6, 2011

I believe module.exports is node.js only and not CommonJS Modules/1.11, which only defines module.id and module.uri. I guess a hasExports would be better if you want it to be universal…

@ryanflorence
Copy link
Author

Good point. Updated.

@thomasdavis
Copy link

This is looking pretty sexy!

@ralphholzmann
Copy link

Starred!

@ryanflorence
Copy link
Author

Note: This is only useful for modules without any dependencies.

@thomasdavis
Copy link

@rplflorence Does it not work if you include dependencies in he define() statement?

@ryanflorence
Copy link
Author

Typically you do define(['dep1', 'dep2'], definition). I don't know how that would fit into this, still brainstorming a bit. The big challenge is un-named modules, which is how I always define them.

@ryanflorence
Copy link
Author

Also, this is bad for static analysis for AMD optimizers like RequireJS, since it looks for specific calls to define.

@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