jquery - 当我配置路径选项时,RequireJs 仅加载 JQuery

标签 jquery requirejs

我的应用程序结构如下所示:

 ...
 javascripts/
    - main.js
    lib/
        - jquery-1.9.0.min.js
        - require.js

我有一个 HTML 页面,例如:

<script type="text/javascript" data-main='/assets/javascripts/main' src='/assets/javascripts/lib/require.js'></script>  

我的 main.js 看起来像:

//main.js
require.config({
    paths: {
    jquery: 'lib/jquery-1.9.0.min' }});

require(['jquery'], function($) {
    return $(function() {
        return console.log('dom ready');
    });
});  

这一切都工作正常,并且 HTML 页面在控制台中显示“dom 就绪”。问题是当我删除路径配置并尝试像这样加载 jquery 时:

//Updated main.js
require(['lib/jquery-1.9.0.min'], function($) {
    return $(function() {
        return console.log('dom ready');
    });
});  

我已经删除了路径配置并尝试通过指定其路径来加载jquery。这给了我关于 $ 变量的“未定义不是函数”。奇怪的是,我仍然看到由 require.js 发起的 jquery-1.9.0.min 通过网络出现。这里发生了什么?这是一个错误吗?

最佳答案

不是错误。 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; } );
}

https://github.com/jquery/jquery/blob/master/src/exports.js

如果您不这样做,那么库仍然会加载(如您所见),但它不会正确返回给您的 require/define 回调

关于jquery - 当我配置路径选项时,RequireJs 仅加载 JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14765830/

相关文章:

javascript - 如何让 html5 颜色选择器在 IE 中工作?

jQuery - 获取 .css() 值并附加到输入值

jquery - 纯 CSS3/HTML5 可折叠菜单?这可能吗?

Node.js 和 Require.js 包含整个目录

javascript - Amazon S3 上的 RequireJS 使用了错误的 URL

jquery - 如果使用 jQuery 不包含 "ul"元素,如何隐藏 "li"元素中的所有内容?

javascript - jQuery 延迟淡入

javascript - Requirejs 出现 knockout 错误 : Unable to process binding "component: function (){return f}" - Mismatched anonymous defined() module

javascript - 使用 require.js 加载 spin.js

javascript - 为什么 KenoUI 的 RequireJS 会带来这么多额外的文件?