我第一次使用require.js,目前一切正常。但是,我开始想要进行构建。我的想法是创建一个包含所有js和模板的文件。但是,每次我使用r.js时,它只包含我的主模块的依赖项。
这是我的app.build.js:
({
appDir: "public/javascripts",
baseUrl: ".",
dir: "build",
paths: {
"hbs": "lib/hbs",
"jquery": "lib/jquery",
"Handlebars": "lib/Handlebars",
"Backbone": "lib/backbone",
"underscore": "lib/underscore",
"bootstrap": "lib/bootstrap.min.js"
},
modules: [{name: "main"}],
shim: {
"bootstrap": {
deps: ["jquery"],
exports: "$.fn.popover"
},
underscore: {
exports: '_'
},
'Handlebars': {
exports: 'Handlebars'
},
Backbone: {
deps: ["underscore", "jquery"],
exports: "Backbone"
}
}})
main.js的开头:
require.config({
paths: {
"hbs": "lib/hbs",
"Handlebars": "lib/Handlebars",
"Backbone": "lib/backbone",
"underscore": "lib/underscore",
"jquery": "lib/jquery",
"bootstrap": "lib/bootstrap.min.js"
},
hbs: {
disableI18n: true
},
shim: {
"bootstrap": {
deps: ["jquery"],
exports: "$.fn.popover"
},
underscore: {
exports: '_'
},
'Handlebars': {
exports: 'Handlebars'
},
Backbone: {
deps: ["underscore", "jquery"],
exports: "Backbone"
}
}
});
require(['jquery', 'Backbone', 'videos'], function($, Backbone, Videos) { // Whatever });
在这种情况下,在我的构建'main.js'中创建的最终文件仅包含:jquery,下划线,主干和视频。我怎样才能确保它还包含模块videos
的依赖关系,即:模板'hbs!template / videos / show'。我怎样才能确保即使在任何地方都不需要bootstrap.min.js?
最后我应该删除require.config,因为它将定义不应该是的路径,因为所有模块都在最终文件中?
答案 0 :(得分:8)
要让优化器包含所有嵌套依赖项,请在构建文件或命令行中包含此选项:
{
findNestedDependencies: true
}
这使得它可以按照您的预期运行,并且您不必将所有依赖项都包含在主文件中。这是一个秘密...我从来没有在文档中看到这个,但我在某个地方的随机博客上看到它。
答案 1 :(得分:3)
在app.build.js中包含指向主配置文件的链接,您可以删除指定的模块,这应该包括主模块使用的所有依赖项。
({
...
mainConfigFile: 'main.js',
...
})
您也可以跳过路径和填充,因为已经在main中指定了。 Bellow是我在我的一个项目中使用的示例配置,并且像魅力一样工作:
({
name: 'main',
baseUrl: '../',
// optimize: 'none',
optimize: 'uglify2',
exclude: ['jquery'],
paths: {
requireLib: 'require'
},
mainConfigFile: '../main.js',
out: '../main.min.js',
// A function that if defined will be called for every file read in the
// build that is done to trace JS dependencies.
// Remove references to console.log(...)
onBuildRead: function (moduleName, path, contents) {
return contents;
// return contents.replace(/console.log(.*);/g, '');
}
})