通常一个 requirejs 模块看起来像:
define('ModuleName', ['jquery', 'underscore', 'backbone'], function($, _, Backbone){
});
因为我设置中的每个文件都需要下划线和主干,所以我希望它们在模块中自动可用,而不必将它们定义为依赖项。
所以像这样:
define('ModuleName', ['jquery'], function($){
$("div.someClass").addClass('hide'); // works
var Model = Backbone.Model.extend(); // works too
});
这可能吗?
如果是,我必须如何寻找或寻找什么关键字?
最佳答案
您感兴趣的模块必须附加到外部范围。默认情况下,Backbone、Underscore、jQuery 等仍然附加到全局范围,除非您对它们调用 noConflict()(并非所有模块都提供这种精确性)。将您的模块附加到全局范围不是一个很好的解决方案,但可以完成您的要求并且无论如何都是默认行为。更好的选择是定义一个外部模块(或只是一个 require() 调用),它除了您命名的子模块之外还包含这些依赖项。否则,使用 RequireJS 的大部分原因都会丢失。
编辑例如:
require(['underscore', 'backbone'],
function (_, Backbone) {
define('ModuleName', ['jquery'], function($){
$("div.someClass").addClass('hide'); // works
var Model = Backbone.Model.extend(); // works too
});
//Other modules here, otherwise this is pointless too
}
);
即便如此,也只有当您在同一个文件中定义多个命名模块时才有用。不幸的是,从我的 Angular 来看,最佳 解决方案是显式导入您的模块并允许隐式模块命名,但上面的示例最接近您的要求。至于隐式模块名称,来自 the RequireJS api docs :
You can explicitly name modules yourself, but it makes the modules less portable -- if you move the file to another directory you will need to change the name.
关于javascript - RequireJs 定义默认 deps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11372709/