RequireJS 网站上最近更新的Use with jQuery页面解释了为什么会发生这种情况以及您可以采取哪些措施来解决它。以下是相关部分:
jQuery 将自己注册为全局变量“$”和“jQuery”,即使它检测到 AMD/RequireJS。AMD 方法建议不要使用全局函数,但关闭这些 jQuery 全局函数的决定取决于您是否有依赖于它们的非 AMD 代码。jQuery 有一个 noConflict 函数,它支持释放对全局变量的控制,这可以在你的 require.config 中自动执行,我们稍后会看到。
如果你想抑制这些全局函数,你需要使用一个map
配置到一个 noConflict 包装模块而不是一个shim
配置。正如@tomaskirda 指出的那样,jQuery 不会触发shim.init
支持 AMD 的库。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 );
});