Is there a way to create a javascript micro-library (a library that has no dependencies), that support all of the following module formats:
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:
/*global jQuery:false, window:false */
// # A method of loading a basic library in AMD, Node.JS require(), jQuery and Javascript's plain old window namespace.
(function(exporterFunction) {
exporterFunction('cll',
function(a,b) {
return a+b;
}
);
})(
(function() { // Gets an exportFunction to normalize Node / Dojo / jQuery / window.*
if ((typeof module != 'undefined') && (module.exports)) { // Node Module
return function(library_name,what_was_exported) {
module.exports = what_was_exported;
return;
};
}
if (typeof define != 'undefined' && define.hasOwnProperty('amd') && define.amd) { // Dojo AMD
return function(library_name,what_was_exported) {
define(function() {
return what_was_exported;
});
};
}
if (typeof jQuery === 'function') { // jQuery Plugin
return function(library_name,source) {
jQuery.fn[library_name] = source;
return;
};
}
if (typeof window != 'undefined') { // Fall down to attaching to window...
return function(library_name,what_was_exported) {
window[library_name] = what_was_exported;
};
}
})(),
(function() {
// ## Other Parameters Here
// You could add parameters to the wrapping function, to include extra
// functionalilty which is dependant upon the environment... See
// https://github.com/forbesmyester/me_map_reduce for ideas.
return 'this_could_be_more_arguments_to_the_main_function';
})()
);
Public Gist available at https://gist.github.com/forbesmyester/5293746