88

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

4

3 に答える 3

104

http://requirejs.org/docs/api.html#config-shimで指摘されているように、RequireJS で shim 構成を使用する際にはいくつかの注意事項があります。つまり、オプティマイザーを使用している場合は、「ビルドで CDN の読み込みと shim 構成を混在させないでください」。

RequireJS の有無にかかわらず、サイトで同じ jQuery プラグイン コードを使用する方法を探していました。https://github.com/umdjs/umd/blob/master/jqueryPlugin.jsで、jQuery プラグインのこのスニペットを見つけました。このコードでプラグインをラップすると、どちらの方法でも適切に動作します。

(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
    };  

}));

クレジットはjrburkeに送られます。多くの JavaScript と同様に、他の関数に作用する関数内の関数です。しかし、私はそれが何をしているのかを解凍したと思います。

最初の行の関数引数factory自体は、$引数でプラグインを定義するために呼び出される関数です。AMD 互換ローダーが存在しない場合は、グローバルjQueryオブジェクトでプラグインを定義するために直接呼び出されます。これは、一般的なプラグイン定義のイディオムに似ています。

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

モジュール ローダーがある場合は、factoryローダーが jQuery をロードした後に呼び出すコールバックとして登録されます。読み込まれた jQuery のコピーが引数です。と同等です

define(['jquery'], function($) {
  $.fn.yourjQueryPlugin = function() {
     // Plugin code here
  };
})
于 2012-08-09T19:04:38.200 に答える