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

How to pass external JSON data to the task from file that generating in previous task?

本文关键字:任务 文件 外部 JSON 数据 上一个      更新时间:2023-09-26

我被困在这里。我有这种类型的任务的咕噜声文件:

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.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.

真的不知道如何弄清楚这一点。有什么想法吗?

如果要填充仅在运行时解析的配置选项,则需要使用模板:

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