【问题标题】:Specifying common modules and dependency in r.js在 r.js 中指定通用模块和依赖项
【发布时间】:2015-07-12 21:39:40
【问题描述】:

我正在使用 requirejs,由于 javascript 文件的数量正在增长,我们计划使用 requirejs 优化器。 由于所有页面都使用了像 (jquery,angular,bootstrap) 这样的 3rd 方 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。

【问题讨论】:

    标签: requirejs dependencies


    【解决方案1】:

    您可以使用bundle,也可以根据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']
        }
    
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-27
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      相关资源
      最近更新 更多