【问题标题】:Correct way to implement jQuery with require.js用 require.js 实现 jQuery 的正确方法
【发布时间】:2013-03-14 20:40:51
【问题描述】:

我正在使用 require.js 和 jQuery 的当前稳定版本,我目前正在包含这样的 jQuery

requirejs.config({
paths: {
    'jQuery': 'vendor/jquery',
}
});

require(['jQuery'], function(jQuery) {
    log(jQuery); // working
});

我没有得到的是,我真的不需要显式返回 jQuery,因为它仍然可以工作(在其他模块中也是如此):

require(['jQuery'], function( // nothing here ) {
    log(jQuery); // working
});

现在我不确定这是否是正确的做法,也是因为使用 $ 美元符号来引用 jQuery 不起作用!

【问题讨论】:

标签: javascript jquery requirejs amd


【解决方案1】:

我看到的关键点:

  1. 当与 RequireJS 一起使用时,jQuery 将自己注册为名为“jquery”的模块(全部小写)。在您的示例中,您尝试将其用作“jQuery”,这有点让人困惑,因为这也是它在加载时注册的全局函数的名称(参见第 2 点)。
  2. 默认情况下,jQuery 使用全局函数“$”和“jQuery”注册自身,即使与 AMD/RequireJS 一起使用也是如此。如果你想关闭这个行为,你必须调用 noConflict 函数。
  3. 您可以在 noConflict 调用中包装 RequireJS 对 jQuery 的引用,如下例所示。据我所知,当您没有其他需要全局 $ 或 jQuery 的模块时,这是推荐的方法:

    requirejs.config({
        paths: {
            'jquery': 'vendor/jquery',
        }
    });
    
    define('jquery-private', ['jquery'], function (jq) {
        return jq.noConflict( true );
    });
    
    require(['jquery-private'], function(jq) {
        console.log(jq);      // working
        console.log($);       // undefined
        console.log(jQuery);  // undefined
    });
    

另请参阅my answer in this question,了解如何映射其他模块以使用私有(无冲突)版本。

有关更多背景信息,请参阅 jQuery 源代码中的这些行,它们是我上面描述的一切的原因:

    // Expose jQuery to the global object
    window.jQuery = window.$ = jQuery;

    // Expose jQuery as an AMD module, but only for AMD loaders that
    // understand the issues with loading multiple versions of jQuery
    // in a page that all might call define(). The loader will indicate
    // they have special allowances for multiple jQuery versions by
    // specifying define.amd.jQuery = true. Register as a named module,
    // since jQuery can be concatenated with other files that may use define,
    // but not use 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.amd.jQuery ) {
        define( "jquery", [], function () { return jQuery; } );
    }

更新:Use with jQuery section of the RequireJS site 已更新以反映上述信息。另请参阅this answer,了解包含优化器的分步操作。只是想再次强调,这种 noConflict 方法仅在 所有您的插件都与 AMD 兼容的情况下才有效。

【讨论】:

  • 我这样做了,我的大部分脚本都可以工作,但在某些情况下,$.fn 是未定义的,即使 $ 看起来没问题...知道为什么吗?
猜你喜欢
  • 1970-01-01
  • 2011-12-03
  • 2010-09-21
  • 1970-01-01
  • 2017-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-28
相关资源
最近更新 更多