【发布时间】:2013-01-07 04:26:08
【问题描述】:
假设我想将 jquery 与使用标准闭包定义的标准、非 amd 启用 jquery 插件一起使用:(function($))( $.fn.myplugin = { ... } )(jQuery);,它都位于 js/libs/jquery/jquery.myplugin.js 内。
我使用这个配置:
require.config({
baseUrl: 'js/',
paths: {
'jquery': 'libs/jquery/jquery-noconflict',
'underscore': 'libs/underscore/underscore',
'backbone': 'libs/backbone/backbone',
'jquery-myplugin': 'libs/jquery/jquery.myplugin'
},
shim: {
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'jquery-myplugin': {
deps: ['jquery']
}
});
我在libs/jquery/jquery-noconflict.js 中以无冲突模式加载 jQuery,因为我不想污染全局命名空间:
define(['libs/jquery'], function () {
return jQuery.noConflict(true);
});
这就是我加载主 app.js 的方式:
define([
'jquery',
'underscore',
'backbone',
'jquery-myplugin'],
function($, _, Backbone, MyPlugin){
//MyPlugin is always undefined, not even sure if
//I should be passing it here if it only extends jQuery?
});
现在,这是我遇到的问题 - 虽然我可以毫无问题地使用上面定义的所有库,但我无法计算出正确的 shim 配置来加载非 AMD 启用的 jquery 插件。
我尝试将 jquery-myplugin 设置为 deps 或 jquery(以及其他方式),但我永远无法让它工作。
我似乎在以下情况下遇到问题:
- jQuery 以无冲突模式加载。
- 插件代码运行,扩展上面的jQuery实例
- 我可以在我的应用程序中使用由插件代码扩展的 $,因此 $.myplugin 可用。
我看到过类似的问题,但没有一个能真正解决这个问题,只给出了模糊的建议,例如“使用 shim config”...
编辑
我也尝试过使用
"jquery-myplugin": {
deps: ["jquery"],
exports: "jQuery.fn.myplugin"
}
虽然通过这种方式加载为 AMD 模块后插件方法可用,但我仍然无法访问:$('.class').myplugin(),因为默认 $ 对象尚未使用 myplugin 代码进行扩展。
【问题讨论】:
-
您还有这个问题吗?
-
模块依赖关系应该用数组表示:
define(['dep1', 'dep2'...'depn'], function(dep1, dep2, ...depn){});,如here所述 -
很好,但这只是我在 stackoverflow 上的错误输入,根本问题仍然存在