RequireJs只在我配置路径选项时加载JQuery

时间:2013-02-08 04:44:04

标签: 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 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发起的网络。这里发生了什么?这是一个错误吗?

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:0)

更改为define而不是require

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