通过grunt任务更新json文件中的文件引用

Cha*_*les 15 javascript build node.js gruntjs

我是一名JavaScript开发人员,从头开始创建构建过程相当新.我选择将Grunt用于我当前的项目,并创建了一个GruntFile,它可以完成我需要它做的大约90%的工作,除了这个问题之外它很有用.当我在文件中开发chrome扩展时,我有几个JavaScript manifest.json文件.对于我的构建过程,我将所有这些文件连接起来并将其缩小为一个文件以包含在其中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",
}
Run Code Online (Sandbox Code Playgroud)

我有一个grunt任务,将上面列出的所有js文件连接并缩小为一个调用的文件,injection.js并且想要一个可以修改清单文件的grunt任务,所以它看起来像这样:

{
    "content_scripts": [{
        "matches": [
            "http://*/*"
        ],
        "js": [
            "js/injection.js"
        ]
    }],
    "version": "2.0",
}
Run Code Online (Sandbox Code Playgroud)

我现在所做的是有两个版本的清单文件,一个用于开发,一个用于构建,在构建过程中它会复制构建版本.这意味着我需要维护两个我不想做的版本.无论如何,与Grunt一起更优雅地做到这一点?

小智 30

Grunt给出了自己的api用于读取和写入文件,我觉得比其他依赖项更好fs:grunt updatejson:key:value在将此任务放入gruntjs文件后使用grunt with command编辑/更新json 文件

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

    });
Run Code Online (Sandbox Code Playgroud)


dc5*_*dc5 11

我做了类似的事情 - 您可以加载清单,更新内容然后再将其序列化.就像是:

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));
});
Run Code Online (Sandbox Code Playgroud)