在 r.js 中指定公共模块和依赖项

Specifying common modules and dependency in r.js

我正在使用 requirejs,由于 javascript 文件的数量在增加,我们计划使用 requirejs 优化器。 由于很少有像 (jquery,angular,bootstrap) 这样的第 3 方 js 被所有页面使用,我认为将所有依赖项放在同一个文件中是一个更好的主意. 假设我们有 2 个文件,employee.js 和 manager.js,我在 build.js 中所做的是

modules[{
name:"person",
include:["jQuery",
"angular",
"bootstrap"
]
},
{
name:"manager",
include:["jQuery",
"angular",
"bootstrap"
]
}]

是否可以将包含的模块列表放在一个公共位置并使用它。 另一个问题是在这种情况下如何指定依赖项?说 Angular 依赖于 jQuery。 在 requirejs 中,有一个配置文件,我可以在其中指定 deps。

您可以使用 bundle or you can create a common module as per the official multipage example,具体取决于您希望实现的目标。您可以在 build.js 中使用变量来避免反复键入相同的依赖项。

另请参阅 mainConfigFile 选项,使用与运行时相同的配置进行构建。

这是一个包定义的例子:

requirejs.config({
    bundles: {
        'primary': ['main', 'util', 'text', 'text!template.html'],
        'secondary': ['text!secondary.html']
    }
});

require(['util', 'text'], function(util, text) {
    //The script for module ID 'primary' was loaded,
    //and that script included the define()'d
    //modules for 'util' and 'text'
});

这是多页示例中构建文件中最相关的部分(但您应该完整地研究该示例):

modules: [
    //First set up the common build layer.
    {
        //module names are relative to baseUrl
        name: '../common',
        //List common dependencies here. Only need to list
        //top level dependencies, "include" will find
        //nested dependencies.
        include: ['jquery',
                  'app/lib',
                  'app/controller/Base',
                  'app/model/Base'
        ]
    },

    //Now set up a build layer for each page, but exclude
    //the common one. "exclude" will exclude
    //the nested, built dependencies from "common". Any
    //"exclude" that includes built modules should be
    //listed before the build layer that wants to exclude it.
    //"include" the appropriate "app/main*" module since by default
    //it will not get added to the build since it is loaded by a nested
    //require in the page*.js files.
    {
        //module names are relative to baseUrl/paths config
        name: '../page1',
        include: ['app/main1'],
        exclude: ['../common']
    },

    {
        //module names are relative to baseUrl
        name: '../page2',
        include: ['app/main2'],
        exclude: ['../common']
    }

]