Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created September 6, 2011 18:10
Show Gist options
  • Select an option

  • Save ryanflorence/1198466 to your computer and use it in GitHub Desktop.

Select an option

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

arian commented Sep 6, 2011

Copy link
Copy Markdown

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
Copy Markdown
Author

Good point. Updated.

@thomasdavis

Copy link
Copy Markdown

This is looking pretty sexy!

@ralphholzmann

Copy link
Copy Markdown

Starred!

@ryanflorence

Copy link
Copy Markdown
Author

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

@thomasdavis

Copy link
Copy Markdown

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

@ryanflorence

Copy link
Copy Markdown
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
Copy Markdown
Author

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

@millermedeiros

Copy link
Copy Markdown

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

jrburke commented Oct 4, 2011

Copy link
Copy Markdown

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