requirejs如何处理jquery?

时间:2013-07-07 02:52:47

标签: jquery requirejs

我正在阅读一些使用requirejs来处理jquery的代码。

使用

require([
'jquery',
], 

function(
$
){} );

我想知道为什么只使用$对所有jquery函数都足够了?

2 个答案:

答案 0 :(得分:1)

如果jquery函数已经定义,jQuery将自己定义define模块。

以下代码位于jquery.js。

if ( typeof module === "object" && module && typeof module.exports === "object" ) {
    // Expose jQuery as module.exports in loaders that implement the Node
    // module pattern (including browserify). Do not create the global, since
    // the user will be storing it themselves locally, and globals are frowned
    // upon in the Node module world.
    module.exports = jQuery;
} else {
    // Otherwise expose jQuery to the global object as usual
    window.jQuery = window.$ = jQuery;

    // Register as a named AMD module, since jQuery can be concatenated with other
    // files that may use define, but not via a proper concatenation script that
    // understands anonymous AMD modules. A named AMD is safest and most robust
    // way to register. Lowercase jquery is used because AMD module names are
    // derived from file names, and jQuery is normally delivered in a lowercase
    // file name. Do this after creating the global so that if an AMD module wants
    // to call noConflict to hide this version of jQuery, it will work.
    if ( typeof define === "function" && define.amd ) {
        define( "jquery", [], function () { return jQuery; } );
    }
}

答案 1 :(得分:0)

看看How to use RequireJS with jQuery

但是,是的,你只需要$(女性与jQuery相同)因为jQuery提供的每个方法(或插件)都封装在该变量中。

如果您使用requirejs加载文件但不这样做,则$将不会定义。

网站示例:

require(['jquery'], function( $ ) {
    console.log( $ ) // OK
});

require(['jquery'], function( jq ) {
    console.log( jq ) // OK
});

require(['jquery'], function( ) {
    console.log( $ ) // UNDEFINED!
});