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

我是一名 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 的文件中,并且想要一个可以修改 list 文件的 grunt 任务,它看起来像这样:

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

我现在所做的是有两个版本的 list 文件,一个用于开发,一个用于构建,在构建过程中它会复制构建版本。这意味着我需要维护 2 个我不想这样做的版本。有没有办法用 Grunt 更优雅地做到这一点?

最佳答案

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

    });

https://stackoverflow.com/questions/17052301/

相关文章:

build - hudson 的 "Started by an SCM change"是什么?

android - 使用-sdk :minSdkVersion 15 cannot be small

c - C语言的sublime text 2构建系统

linux - 在 Debian 或 Ubuntu 下自动获取构建依赖项的 Debian 方式是什么

c# - 从构建输出中省略程序集的本地化版本

time - Jenkins——使用 "Build Time Trend"获取 "Remote Ac

build - 如何在 VSTS/VSO Build vNext 中创建 Web 部署包?

android - 指示 Android Gradle 脚本删除未对齐的 apk 并清理 Artif

makefile - cmake和并行构建与 "make -jN"

xcode - 如何将编译源中的文件从一个目标复制并粘贴到另一个目标?