我被这个问题困在这里了。 我有包含此类任务的 gruntfile:
grunt.initConfig({
shell: {
// stub task; do not really generate anything, just copy to test
copyJSON: {
command: 'mkdir .tmp && cp stub.json .tmp/javascripts.json'
}
},
uglify: {
build: {
files: {
'output.min.js': grunt.file.readJSON('.tmp/javascripts.json')
}
}
},
clean: {
temp: {
src: '.tmp'
}
}
});
grunt.registerTask('build', [
'shell:copyJSON',
'uglify:build',
'clean:temp'
]);
当然,这是行不通的,因为没有 .tmp/javascripts.json
文件:
Error: Unable to read ".tmp/javascripts.json" file (Error code: ENOENT).
我尝试执行额外的任务,在生成文件后创建变量,尝试将其存储在 globals.javascript
和 grunt.option("JSON")
,像这样:
grunt.registerTask('exportJSON', function() {
if (grunt.file.exists('.tmp/javascripts.json')) {
grunt.log.ok("JSON with set of javascripts exist");
grunt.option("JSON", grunt.file.readJSON('.tmp/javascripts.json'));
}
else {
grunt.fail.warn("JSON with set of javascripts does not exist");
};
});
grunt.initConfig({
uglify: {
build: {
files: {
'output.min.js': grunt.option("JSON")
}
}
}
});
grunt.registerTask('build', [
'shell:copyJSON',
'exportJSON',
'uglify:build',
'clean:temp'
]);
并且总是出现相同的错误警告:无法调用未定义的方法“indexOf”使用--force继续。
真的不知道如何解决这个问题。有什么想法吗?
最佳答案
如果您想填充仅在运行时解析的配置选项,则需要使用模板:
http://gruntjs.com/configuring-tasks#templates
简单来说,您需要将 uglify
任务的 files
配置更改为以下内容:
files: {
'output.min.js': "<%= grunt.option('JSON') %>"
}
还可以选择使用 grunt.config.set
更改 uglify
任务的配置:
grunt.registerTask('exportJSON', function() {
if (grunt.file.exists('.tmp/javascripts.json')) {
grunt.log.ok("JSON with set of javascripts exist");
files = grunt.file.readJSON('.tmp/javascripts.json');
grunt.config.set(
['uglify', 'build', 'files', 'output.min.js'], files
);
} else {
grunt.fail.warn("JSON with set of javascripts does not exist");
}
});
在这种情况下,您的 uglify
任务的 files
选项需要类似于:
files: {
'output.min.js': ''
}
关于javascript - 如何将外部 JSON 数据从上一个任务中生成的文件传递到任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19524226/