javascript – RequireJs定义默认代码

通常一个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
    }
);

即使这只在您在同一文件中定义多个命名模块时才有用.不幸的是,从我的角度来看,最好的解决方案是显式导入模块并允许隐式模块命名,但上面的示例最接近您的要求.至于隐式模块名称,从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.

点赞