supporting both CommonJS and AMD

后端 未结 6 2254
臣服心动
臣服心动 2020-11-29 18:15

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
6条回答
  •  粉色の甜心
    2020-11-29 19:02

    I have solved this exact problem and managed to easily support:

    • Dojo AMD (referencing the RequireJS specs)
    • jQuery (under $/jQuery.fn.[your_library_here])
    • node.js using vanilla require('path_to.js')
    • Browser window.[your_library_here]

    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

提交回复
热议问题