我正在开发一个使用jQuery的JavaScript模块,jQuery UI(draggable)和jPlayer的一些功能。最近我让自己熟悉requireJS来正确管理依赖项。
我不想与包含我的脚本的网站可能已经存在的jQuery版本产生冲突。出于这个原因,我通过调用noConflict()将jQuery依赖项映射到模块“jquery-private”,如requireJS guide中所述。
由于jQuery UI占用了大量空间,我还想包含我实际使用的模块。 ui.draggable有依赖关系ui.core,ui.mouse和ui.widget,所以我应该包含这4个模块。
我的问题是我希望jQuery UI模块和jPlayer模块使用我自己的jQuery版本,但显然在调用noConflict()方法后,全局$变量无法访问它。不幸的是,jQuery UI和jPlayer都不是AMD模块,因此我需要为它们制作垫片配置。
以下是我对依赖项的定义:
require.config({
baseUrl: 'javascript/modules',
paths: {
jquery: 'jquery-2.1.3',
jPlayer: 'jquery.jplayer',
uiCore: 'jquery.ui.core',
uiMouse: 'jquery.ui.mouse',
uiWidget: 'jquery.ui.widget',
uiDraggable: 'jquery.ui.draggable'
},
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' }
},
shim: {
jPlayer: {
deps: ['jquery']
},
uiCore: {
deps: ['jquery']
},
uiMouse: {
deps: ['jquery','uiCore']
},
uiWidget: {
deps: ['jquery','uiCore']
},
uiDraggable: {
deps: ['jquery','uiCore','uiMouse','uiWidget']
}
}
});
require(["json","jquery","jPlayer","uiDraggable"], function(json,___jQuery,jplayer,uiDraggable) {
(...)
}
显然,由于未定义jQuery UI模块中的$变量,此代码会产生错误。
有没有办法将我自己的jQuery对象传递给模块?另一个帖子(How use require.js to load jQuery with noConflict)中的最佳答案表明我想做的事情是不可能的,但也许还有其他方法可以做到这一点?
如果没有,我可能不得不使用全局变量并大量编辑所包含的模块,这使得为什么首先使用像requireJS这样的依赖管理库有疑问......
答案 0 :(得分:0)
我在jquery.ui中的每个模块的顶部找到了以下代码:
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "jquery" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {...});
这意味着jquery.ui检查全球AMD"定义"函数已定义并使用' jquery'作为AMD参考模块。
根据this和this中的requirejs建议,它不会使用jquery冲突。
关于AMD的how to use jQuery。