How to make a jQuery plugin loadable with requirejs

后端 未结 3 1256
迷失自我
迷失自我 2020-12-07 07:21

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.

3条回答
  •  长情又很酷
    2020-12-07 08:01

    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.

提交回复
热议问题