Is there a way to create a javascript micro-library (a library that has no dependencies), that support all of the following module formats:
- Asynchronous Module Definition
- CommonJS
- exposing the library's exports as a global namespace object (no loader)
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!
Yes, and I owe this answer to ded and his awesome modules:
This can then be used:
in AMD (e.g. with requireJS):
in commonJS (e.g. nodeJS):
globally (e.g. in HTML):
This method needs to get more publicity - if jQuery and co. started using it life would be much easier!
Just to update a little bit on this answer in regards to @marc I too give credit to ded and have updated it a bit to be with the latest updates:
Object at the end is a reference to either the parent or the current scope, lets say you have a package you are writing and this is just a piece of the pie, well that context could be a name-spaced object and this is just a slice of that pie.
Also, if you wish to have dependencies, there is an optional parameter at the end after your scope which supports an array, in this case the definition parameter then can utilize each dependency as a argument. Also, the dependencies listed in an array will be required inside node-js platform for your convenience sake.
See: https://gist.github.com/Nijikokun/5192472 for a real example.
I have solved this exact problem and managed to easily support:
It's using a combination of dependency injection and IIFE to get the job done.
See Below:
Public Gist available at https://gist.github.com/forbesmyester/5293746
This is based on Nijikokun's answer. Since RequireJS discourages the use of explicit module names this has been omitted in this version. The second argument to the loader describe the dependencies. Pass
[]
if you don't need to load any.