Grunt Run in a For Loop

北慕城南 提交于 2019-12-11 03:08:40

问题


I'm new to grunt.

I have a gruntfile that works for a single build. There are several target that are chained together to complete the process. The problem is that I need to create several different builds using variable data. I'm trying to figure out how to do this in my gruntfile.

Today, to do a build, I just need to run

grunt --foo=bar build

or

grunt --foo=baz build

What I'd like to, and have tried to do, is create a build-all target that uses an array to define the foo data, like so:

grunt.registerTask('build-all', function() {
    var foos = ["bar", "baz"];
    for (var i in foos) {
        grunt.config.set("foo", foos[i]);
        grunt.task.run("build");
    }
});

From the looks of things, it seems that the run task is non-blocking. And that means that "foo" is being set to "baz" before the first run, running it twice for the same value.

Is there a better way to set arguments/options in this situation? Or to run the task in a blocking way?


回答1:


I recently ran up against this same issue, and wrote grunt-galvanize to help with this. Here's how it works, applied to your example:

grunt.registerTask('build-all', function() {
    var foos = ["bar", "baz"];
    var galvanizeConfig = [];

    for (var i in foos) {
        galavanizeConfig.push({configs: {foo: foos[i]}});
    }
    grunt.option('galvanizeConfig', galvanizeConfig);
    grunt.task.run(['galvanize:build']);
});

This will run the build task with each of the options/configs specified in galvanizeConfig.

PS. I also use grunt-multi for cases where I desire concurrency, but grunt-galvanize is a much simpler tool for cases where concurrency is not required.



来源:https://stackoverflow.com/questions/26025396/grunt-run-in-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!