-
-
Save ryanflorence/1198466 to your computer and use it in GitHub Desktop.
(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(); |
Good point. Updated.
This is looking pretty sexy!
Starred!
Note: This is only useful for modules without any dependencies.
@rplflorence Does it not work if you include dependencies in he define() statement?
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.
Also, this is bad for static analysis for AMD optimizers like RequireJS, since it looks for specific calls to define.
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..
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.
I believe
module.exports
is node.js only and not CommonJS Modules/1.11, which only definesmodule.id
andmodule.uri
. I guess ahasExports
would be better if you want it to be universal…