如何使用require.js加载带有noConflict的jQuery [英] How use require.js to load jQuery with noConflict
问题描述
我正在尝试使用require
I am trying to load jquery in noConflict mode by using require
require.config({
paths: {
'jquery': 'libs/jquery-req',
underscore: 'libs/underscore',
backbone: 'libs/backbone'
},
shim: {
jquery: {
init: function() {
console.log('jq init');
var jq = this.jQuery.noConflict(true);
jq.support.cors = true;
return jq;
},
exports: '$'
},
backbone: {
deps: ['underscore', 'jquery'],
init: function() {
console.log('b init');
},
exports: 'Backbone'
},
underscore: {
exports: '_'
}
}
});
并使用它:
define([
'jquery',
'underscore',
'backbone'
], function(jq, _, Backbone) {
console.log(jq);
var initialize = function() {
// Router.initialize();
};
return {
initialize: initialize
};
});
不幸的是,似乎shim.jquery.init函数从未被调用过。有人可以帮我理解为什么吗?当我重命名jquery时,有什么奇怪的 - > jquery-reg然后它似乎工作,但它需要更改每个文件中定义的依赖项。
unfortunately it seems shim.jquery.init function is never called. Can someone try to help me understand why? What is strange when I rename jquery -> jquery-reg then it seems to work, but it requires to change dependency defined in every files.
推荐答案
创建以下noconflict.js模块:
Create the following noconflict.js module:
define(["jquery"], function($) {
//drop the `true` if you want jQuery (but not $) to remain global
return $.noConflict(true);
});
然后,在您的require.config中添加:
Then, in your require.config add:
map: {
"*": {
"jquery": "noconflict"
},
"noconflict": {
"jquery": "jquery"
}
}
jQuery的noconflict版本将交给所有模块(noconflict除外)。摆脱jQuery垫片。
The noconflict version of jQuery will be handed to all modules (except noconflict). Get rid of the jQuery shim.
请注意,保持jQuery不在全局命名空间的路径将阻止你使用任何非AMD的jQuery插件将这些插件修改为AMD模块。 Shim没有做任何神奇的事情来利用这个设置。对于你可能想要垫片的任何非AMD模块也是如此,这取决于你所做的纯粹AMD。
Please note that going the path of keeping jQuery out of the global namespace will prevent you from using any jQuery plugins that are non-AMD without modifying those plugins to be AMD modules. Shim doesn't do anything magical to take advantage of this setup. The same goes for any non-AMD module you might want to shim that depends on something you've made "pure" AMD.
这篇关于如何使用require.js加载带有noConflict的jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!