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

标签 javascript json node.js variables gruntjs

我被这个问题困在这里了。 我有包含此类任务的 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.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'
]);

并且总是出现相同的错误警告:无法调用未定义的方法“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/

相关文章:

javascript - Jquery Post 无法正常工作?

c# - 无法从 json 结果 MVC 4 中检索值

sql - 使用 PostgreSQL10 根据行中的值分层聚合 JSON

javascript - Coffeescript 需要带参数的模块,browserify

javascript - 像这样写图片和链接

javascript - 如何使用 php、ajax 和 jquery 将数据库中的设置值调用到 <label> 中

java - 提交值后如何清除表单?

android - 改造 - 在将其解析为 json 之前从响应主体中删除一些无效字符

javascript - React Native - 警告 : Can't perform a React state update on an unmounted component

javascript - NodeJs 服务器卡住,ctrl+c 偶尔会解冻