如何将外部JSON数据从前一个任务中生成的文件传递给任务?

我被困在这里了。 我有这种types的任务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' ]); 

而且,cource,这是行不通的,因为没有.tmp/javascripts.json文件:

 Error: Unable to read ".tmp/javascripts.json" file (Error code: ENOENT). 

我已经尝试做额外的任务创build文件后生成的variables,试图将其存储在globals.javascriptgrunt.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' ]); 

并始终有一个相同的错误Warning: Cannot call method 'indexOf' of undefined Use --force to continue.

真的不知道如何解决这个问题。 有任何想法吗?

如果你想填充一个configuration选项,只有在运行的时候才能parsing,你需要使用模板:

http://gruntjs.com/configuring-tasks#templates

所以简单地说,你需要将uglify任务的filesconfiguration更改为以下内容:

 files: { 'output.min.js': "<%= grunt.option('JSON') %>" } 

还可以使用grunt.config.set任务的configuration:

 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': '' }