【发布时间】:2016-03-18 10:08:17
【问题描述】:
我正在设置一系列与 RequireJS r.js 编译器一起使用的 grunt 任务: 1) 生成目录中所有文件的 .json 文件列表 2)从文件名中删除“.js”(requirejs需要这个) 3) 使用 grunt.file.readJSON() 解析该文件并在我的 requirejs 编译任务中用作配置选项。
这是我的 gruntfile.js 中的相关代码:
module.exports = function (grunt) {
grunt.initConfig({
// create automatic list of all js code modules for requirejs to build
fileslist: {
modules: {
dest: 'content/js/auto-modules.json',
includes: ['**/*.js', '!app.js', '!libs/*'],
base: 'content/js',
itemTemplate: '\t{' +
'\n\t\t"name": "<%= File %>",' +
'\n\t\t"exclude": ["main"]' +
'\n\t}',
itemSeparator: ',\n',
listTemplate: '[' +
'\n\t<%= items %>\n' +
'\n]'
}
},
// remove .js from filenames in module list
replace: {
nodotjs: {
src: ['content/js/auto-modules.json'],
overwrite: true,
replacements: [
{ from: ".js", to: "" }
]
}
},
// do the requirejs bundling & minification
requirejs: {
compile: {
options: {
appDir: 'content/js',
baseUrl: '.',
mainConfigFile: 'content/js/app.js',
dir: 'content/js-build',
modules: grunt.file.readJSON('content/js/auto-modules.json'),
paths: {
jquery: "empty:",
modernizr: "empty:"
},
generateSourceMaps: true,
optimize: "uglify2",
preserveLicenseComments: false,
//findNestedDependencies: true,
wrapShim: true
}
}
}
});
grunt.loadNpmTasks('grunt-fileslist');
grunt.loadNpmTasks('grunt-text-replace');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.registerTask('default', ['fileslist','replace', 'requirejs']);
我遇到了一个问题,如果“content/js/auto-modules.json”文件在加载我的配置文件时不存在,则 file.readJSON() 在文件存在并且整个任务失败并抛出“错误:无法读取文件”如果文件已经存在,一切正常。
如何进行设置,以便任务配置等待在第一个任务中创建该文件,并在第二个任务中对其进行修改,然后再尝试为第三个任务加载和解析其中的 JSON?还是有另一种方法(可能使用不同的插件)在一个任务中生成一个 json 对象,然后将该对象传递给另一个任务?
【问题讨论】:
-
你找到解决方案了吗?
标签: gruntjs