1

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

 ...
 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 ready”。问题是当我删除路径配置并尝试像这样加载 jquery 时:

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

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

4

2 回答 2

4

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

如果你不这样做,那么库仍然会加载(如你所见),但它不会正确返回给你需要/定义回调

于 2013-02-08T07:31:03.147 回答
0

改为define而不是require

define(['lib/jquery-1.9.0.min'], function($) {
    return $(function() {
        return console.log('dom ready');
    });
}); 
于 2013-02-08T04:55:43.053 回答