supporting both CommonJS and AMD
Yes, and I owe this answer to ded and his awesome modules:
(function(name, definition) {
if (typeof module != 'undefined') module.exports = definition();
else if (typeof define == 'function' && typeof define.amd == 'object') define(definition);
else this[name] = definition();
}('mod', function() {
//This is the code you would normally have inside define() or add to module.exports
return {
sayHi: function(name) {
console.log('Hi ' + name + '!');
}
};
}));
This can then be used:
-
in AMD (e.g. with requireJS):
requirejs(['mod'], function(mod) { mod.sayHi('Marc'); });
-
in commonJS (e.g. nodeJS):
var mod = require('./mod'); mod.sayHi('Marc');
-
globally (e.g. in HTML):
<script src="mod.js"></script> <script>mod.sayHi('Marc');</script>
This method needs to get more publicity - if jQuery and co. started using it life would be much easier!
Here is a list of various cross-compatible module formats.
I suspect that the one you're looking for is what they're calling "commonjsStrict.js"
uRequire, the Universal Module & Resource Converter is the tool that does exactly that.
It mainly converts AMD and CommonJS to UMD / AMD / CommonJS / Plain script (no AMD loader required).
It allows declarative exporting of modules, with a
noConflict()
baked in.It can manipulate modules (inject/replace/remove dependencies OR code) as you build them.
It converts from coffeescript, coco, Livescript, icedCoffeescript and you can add your own conversions in one liners!