Can I write a javascript file that optionally uses require.js to specifies dependencies when it is available?

前端 未结 1 1718
青春惊慌失措
青春惊慌失措 2021-01-25 07:26

I need to write a javascript plugin that can be used both as an AMD module and as a non-AMD (synchronously loaded) javascript file.

It has a dependency on the \"Jockey

1条回答
  •  隐瞒了意图╮
    2021-01-25 07:54

    It can be done. I've got one such plugin right here. Here's the general structure:

    (function (factory) {
        // If in an AMD environment, define() our module, else use the
        // jQuery global.
        'use strict';
        if (typeof define === 'function' && define.amd)
            define(['jquery'], factory);
        else
            factory(jQuery);
    }(function ($) {
        'use strict';
    
        // This is the plugin proper.
        $.fn.myMethod = function(/* ... */) {
            // Code for the method...
        };
    }));
    

    A plugin that needs other things than just jQuery would use the structure above with the following modifications:

    1. A call to define that lists the additional modules needed.

    2. A factory(jQuery) call (in the non AMD branch, used when RequireJS is not loading the plugin) that passes additional values from the global space after jQuery.

    3. A factory function function ($) that has additional arguments to receive the additional values passed to it.

    So if the plugin needs module foo which exports itself in the global space as foo and with a RequireJS configuration that names it "foo", then:

    (function (factory) {
        // If in an AMD environment, define() our module, else use the
        // jQuery global.
        'use strict';
        if (typeof define === 'function' && define.amd)
            define(['jquery', 'foo'], factory);
        else
            factory(jQuery, foo);
    }(function ($, foo) {
        'use strict';
    
        // This is the plugin proper.
        $.fn.myMethod = function(/* ... */) {
            // Code for the method...
            foo.blah();
        };
    }));
    

    0 讨论(0)
提交回复
热议问题