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

StackOverflow https://stackoverflow.com/questions/21351621

  •  02-10-2022
  •  | 
  •  

Question

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.js" and jquery libraries.

In other words, I'd like to structure the file so that it doesn't fail when its used in a traditional non-async html structure (loaded via a script tag, after its dependencies are loaded via script tags), but so that it will also be able to work as an AMD module without shim, and specify its dependencies. Can this be done, or is shim the only way to do this?

Était-ce utile?

La solution

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();
    };
}));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top