问题
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