我想摆脱全局 jQuery 对象(window.$,也许还有 window.jQuery)。
主要数据:
require.config({
paths: {
"jquery": "jquery-2.0.0"
},
shim: {
"bootstrap": {
deps: ["jquery"]
},
"jquery": {
deps: [],
init: function() {
return this.jQuery.noConflict(true);
},
exports: "jQuery"
}
}
});
require(["jquery", "bootstrap"], function($) {
// ...
});
这段代码有什么问题?永远不会调用“init”。
最佳答案
最近更新的Use with jQuery RequireJS 网站上的页面解释了更多关于为什么会发生这种情况以及您可以采取什么措施来解决它。这是相关部分:
jQuery registers itself as the global variables "$" and "jQuery", even when it detects AMD/RequireJS. The AMD approach advises against the use of global functions, but the decision to turn off these jQuery globals hinges on whether you have non-AMD code that depends on them. jQuery has a noConflict function that supports releasing control of the global variables and this can be automated in your require.config, as we will see later.
如果你想抑制这些全局函数,你需要使用 map
配置到 noConflict 包装器模块,而不是 shim
配置。正如@tomaskirda 指出的那样,jQuery 不会为支持 AMD 的库触发 shim.init
。相关代码来自Use with 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 );
});
关于javascript - require.js jQuery noConflict shim - 为什么从不调用 init 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16736663/