通过一个咕噜任务更新json文件中的文件引用

我是一名JavaScript开发人员,从头开始创build构build过程相当新颖。 我select使用Grunt来处理当前的项目,并且创build了一个GruntFile,这个GruntFile约占我需要的90%,除了这个问题之外,它工作的很好。 我有几个JavaScript文件,我在manifest.json文件中开发chrome扩展时引用。 对于我的构build过程,我连接所有这些文件,并将其缩小到一个文件,以包含在manifest.json 。 有没有在生成过程中更新manifest.json文件中的文件引用,所以它指向缩小版本?

这是src清单文件的一个片段:

 { "content_scripts": [{ "matches": [ "http://*/*" ], "js": [ "js/lib/zepto.js", "js/injection.js", "js/plugins/plugin1.js", "js/plugins/plugin2.js", "js/plugins/plugin3.js", "js/injection-init.js" ] }], "version": "2.0", } 

我有一个长长的任务,将上面列出的所有js文件连接并缩小到一个名为inject.js的文件中,并且想要一个可以修改清单文件的grunt任务,如下所示:

 { "content_scripts": [{ "matches": [ "http://*/*" ], "js": [ "js/injection.js" ] }], "version": "2.0", } 

我现在所做的是有两个版本的清单文件,一个用于开发,另一个用于构build,在构build过程中,它复制构build版本。 这意味着我需要保持2个版本,我宁愿不要做。 有没有办法更好地与Grunt做这个?

Grunt为读写文件提供了自己的api,我感觉比其他依赖如fs更好:使用grunt使用grunt编辑/更新json文件grunt updatejson:key:value在将这个任务放入gruntjs文件后的值

 grunt.registerTask('updatejson', function (key, value) { var projectFile = "path/to/json/file"; if (!grunt.file.exists(projectFile)) { grunt.log.error("file " + projectFile + " not found"); return true;//return false to abort the execution } var project = grunt.file.readJSON(projectFile);//get file as json object project[key]= value;//edit the value of json object, you can also use projec.key if you know what you are updating grunt.file.write(projectFile, JSON.stringify(project, null, 2));//serialize it back to file }); 

我做类似的事情 – 你可以加载你的清单,更新内容然后再次序列化。 就像是:

 grunt.registerTask('fixmanifest', function() { var tmpPkg = require('./path/to/manifest/manifest.json'); tmpPkg.foo = "bar"; fs.writeFileSync('./new/path/to/manifest.json', JSON.stringify(tmpPkg,null,2)); }); 

我不同意这里的其他答案。

1)为什么使用grunt.file.write而不是fsgrunt.file.write 只是 grunt.file.write一个包装 (见这里的代码)。

2)为什么使用fs.writeFileSync时使用fs.writeFileSync可以非常容易地asynchronous执行内容? 毫无疑问,在构build过程中你不需要asynchronous,但如果这很容易做到, 为什么不呢? (事实上​​,只有一些字符比writeFileSync实现长。)

我会build议如下:

 var fs = require('fs'); grunt.registerTask('writeManifest', 'Updates the project manifest', function() { var manifest = require('./path/to/manifest'); // .json not necessary with require manifest.fileReference = '/new/file/location'; // Calling this.async() returns an async callback and tells grunt that your // task is asynchronous, and that it should wait till the callback is called fs.writeFile('./path/to/manifest.json', JSON.stringify(manifest, null, 2), this.async()); // Note that "require" loads files relative to __dirname, while fs // is relative to process.cwd(). It's easy to get burned by that. });