gpt4 book ai didi

javascript - 将私有(private) jquery 与 RequireJS 结合使用 - 优化后的问题

转载 作者:行者123 更新时间:2023-11-29 17:16:08 25 4
gpt4 key购买 nike

我正在使用 requireJS 和 jQuery 的 CDN 版本(这是现在推荐的方法)构建一个框架,并且在优化代码时遇到了一些问题。输出是命名空间的,我指定每个模块都使用私有(private)版本的 jquery,如文档中所述:

require.config({
// Add this map config in addition to any baseUrl or
// paths config you may already have in the project.
map: {
// '*' means all modules will get 'jquery-private'
// for their 'jquery' dependency.
'*': { 'jquery': 'jquery-private' },

// 'jquery-private' wants the real jQuery module
// though. If this line was not here, there would
// be an unresolvable cyclic dependency.
'jquery-private': { 'jquery': 'jquery' }
}
});

// and the 'jquery-private' module, in the
// jquery-private.js file:
define(['jquery'], function (jq) {
return jq.noConflict( true );
});

我在优化后看到的问题是“jquery-private.js”文件中的“jq”未定义。

有什么想法吗?我试过设置 jq = $ 但这似乎破坏了全局。

谢谢。

最佳答案

这是我为获得 jQuery CDN & optimization sample 所做的工作从 RequireJS jQuery Instructions page 链接与 Mapping Modules to use noConflict 一起工作您在原始问题中粘贴的部分。

1 - fork sample

2 - 使用此内容创建文件 www/js/lib/jquery-private.js

define(['jquery'], function (jq) {
return jq.noConflict( true );
});

3 - 修改了 www/js/app.js 以粘贴 map 部分,因此 require.config 现在看起来像这样:

requirejs.config({
"baseUrl": "js/lib",
"paths": {
"app": "../app",
"jquery": "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min"
},
map: {
'*': { 'jquery': 'jquery-private' },
'jquery-private': { 'jquery': 'jquery' }
}
});

4 - 修改了 www/js/app/main.js 以使用 jqlocal 而不是 $ (只是为了向自己证明它是不是全局 jQuery:

define(["jquery", "jquery.alpha", "jquery.beta"], function(jqlocal) {
jqlocal(function() {
jqlocal('body').alpha().beta();
});
});

5 - 更改为 tools 文件夹并运行:

node r.js -o build.js

6 - 更改为创建并运行 servedirwww-build 文件夹(什么网络服务器并不重要,但这就是我用于开发的)

7 - 浏览到应用程序的本地地址和端口号(在我的例子中是 http://localhost:8000/app.html)并看到:

Alpha is Go!

Beta is Go!

可以看到最终结果here

关于javascript - 将私有(private) jquery 与 RequireJS 结合使用 - 优化后的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17615594/

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