我是一名JavaScript开发人员,并且是从头开始创建构建过程的新手。我选择在当前项目中使用Grunt,并创建了一个GruntFile,它可以完成我需要执行的操作的90%,并且效果很好,除了这一问题。在manifest.json文件中开发chrome扩展程序时,我有几个引用的JavaScript文件。对于我的构建过程,我将所有这些文件串联在一起,并将其最小化为一个文件,以包含在manifest.json中。无论如何,在构建过程中是否需要更新manifest.json文件中的文件引用,以便它指向压缩后的版本?

这是src list 文件的片段:

{
    "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",
}

我有一个grunt任务,它将上面列出的所有js文件串联并缩小为一个名为injection.js的文件,并且想要一个grunt任务,可以修改 list 文件,因此它看起来像这样:
{
    "content_scripts": [{
        "matches": [
            "http://*/*"
        ],
        "js": [
            "js/injection.js"
        ]
    }],
    "version": "2.0",
}

我现在要做的是 list 文件有2个版本,一个用于dev,一个用于build,在构建过程中它将复制构建版本。这意味着我需要维护两个我不愿意做的版本。无论如何,Grunt可以更优雅地做到这一点吗?

最佳答案

Grunt提供了自己的用于读取和写入文件的api,我觉得比fs等其他依赖项更好:
将此任务放入gruntjs文件后,使用grunt与grunt updatejson:key:value命令编辑/更新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

    });

09-10 10:19
查看更多