我正在使用require.js和jQuery的当前稳定版本,我目前正在包含这样的jQuery
requirejs.config({
paths: {
'jQuery': 'vendor/jquery',
}
});
require(['jQuery'], function(jQuery) {
log(jQuery); // working
});
我没有得到的是我并不需要明确地回馈jQuery,因为这仍然有效(在其他模块中也是如此):
require(['jQuery'], function( // nothing here ) {
log(jQuery); // working
});
现在我不确定这是否是正确的方法,也因为使用$ dollar符号来引用jQuery不起作用!
答案 0 :(得分:39)
我看到的关键点:
您可以在noConflict调用中将RequireJS引用包装到jQuery,如下例所示。据我所知,当你没有其他模块需要全局$或jQuery时,这是推荐的方法:
requirejs.config({
paths: {
'jquery': 'vendor/jquery',
}
});
define('jquery-private', ['jquery'], function (jq) {
return jq.noConflict( true );
});
require(['jquery-private'], function(jq) {
console.log(jq); // working
console.log($); // undefined
console.log(jQuery); // undefined
});
另见my answer in this question关于如何映射其他模块以使用私有(noConflict)版本。
有关更多背景信息,请参阅jQuery源代码中的这些行,这些是上述所有内容的原因:
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
更新: Use with jQuery section of the RequireJS site已更新,以反映上述信息。有关优化程序的详细步骤,另请参阅this answer。只想再次强调一下,这种noConflict方法只有在所有你的插件与AMD兼容时才有效。