Nicola Peluchetti Nicola Peluchetti - 3 months ago 27
Javascript Question

How to make a jQuery plugin loadable with requirejs

I'm working with requirejs+jquery and i was wondering if there was a smart way to make a jQuery plugin work well with require.

For example i'm using jQuery-cookie. If i understood correctly i can create a file called jquery-cookie.js and inside do

define(["jquery"], // Require jquery
function($){
// Put here the plugin code.
// No need to return anything as we are augmenting the jQuery object
});
requirejs.config( {
"shim": {
"jquery-cookie" : ["jquery"]
}
} );


i wondered if i could do things like jQuery does, which is like this:

if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}


or if this is the only way to make jQuery plugins compatible with requirejs or any amd

Answer

You only need to do EITHER

define(["jquery"], // Require jquery
       function($){
// Put here the plugin code. 
// No need to return anything as we are augmenting the jQuery object
});

at the end of jquery-cookie.js, OR

requirejs.config( {
    "shim": {
        "jquery-cookie"  : ["jquery"]
    }
} );

anywhere before you include jquery-cookie (like wherever data-main points to, for instance).

The last code block you've posted is good for things like jQuery which get redistributed and may or may not be in an AMD environment. Ideally every jQuery plugin would have that set up already.

I prefer to keep included libraries as unadulterated as possible, so the global shim config once per page seems like the cleanest solution to me. That way upgrades are safer and CDNs become a possibility.

Comments