How to make a jQuery plugin loadable with requirejs

51,993

Solution 1

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.

Solution 2

There are some caveats with using shim configuration in RequireJS, pointed out on http://requirejs.org/docs/api.html#config-shim. Namely, "Do not mix CDN loading with shim config in a build" when you're using the optimizer.

I was looking for a way to use the same jQuery plugin code on sites both with and without RequireJS. I found this snippet for jQuery plugins at https://github.com/umdjs/umd/blob/master/jqueryPlugin.js. You wrap your plugin in this code, and it will work properly either way.

(function (factory) {
if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module depending on jQuery.
    define(['jquery'], factory);
} else {
    // No AMD. Register plugin with global jQuery object.
    factory(jQuery);
}
}(function ($) {

    $.fn.yourjQueryPlugin = function () {
        // Put your plugin code here
    };  

}));

Credit goes to jrburke; like so much javascript, it's functions inside functions acting on other functions. But I think I have unpacked what it's doing.

The function argument factory in the first line is itself a function which is invoked to define the plugin on the $ argument. When no AMD-compatible loader is present, it's invoked directly to define the plugin on the global jQuery object. That's just like the common plugin definition idiom:

function($)
{
  $.fn.yourjQueryPlugin = function() {
    // Plugin code here
  };
}(jQuery);

If there is a module loader, then factory is registered as the callback for the loader to invoke after loading jQuery. The loaded copy of jQuery is the argument. It's equivalent to

define(['jquery'], function($) {
  $.fn.yourjQueryPlugin = function() {
     // Plugin code here
  };
})

Solution 3

Just as an FYI to all some of the jquery plugins already use amd/require so you dont need to declare anything in the shim. In fact doing so might cause problems for you in some cases.

If you look in the jquery cookie JS you will see define calls and require(["jquery"]).

and in jquery.js you will see a call to define("jquery",[],function()...

Share:
51,993
Nicola Peluchetti
Author by

Nicola Peluchetti

I've 10 years of full stack development experience: 6 with important agencies ( 10up, Webscience, Politecnico ), 3 with a startup and 1 freelancing. In the last year I worked on a huge migration from a static/PHP site to WordPress, on a React Native App ( yes, a social network, 2018), on a React search page backed by Elastic Search, on a WP REST api for a React Back End and more. My main expertise is in the WordPress environment ( Woocommerce and WordPress VIP experience too ), but I also have production experience with React, React Native, Java, node.js, Elastic Search, Zend Framework, Drupal 8, SQL, Saas, Less, Backbone, Webpack, MQL4 and Grunt. I'm a fast learner and prefer to work in places where you can code in multiple languages. I'm looking for remote contract work in the US Eastern timezone. I've been in the top 100 on StackOverflow twice: number 63 on the site in July 2011 and number 73 in March 2012 http://stackexchange.com/leagues/1/month/stackoverflow/2012-03-01/397861?sort=reputationchange#397861

Updated on July 08, 2022

Comments

  • Nicola Peluchetti
    Nicola Peluchetti almost 2 years

    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