gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:20:05 24 4
gpt4 key购买 nike

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

 ...
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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com