grunt.task.run 上带有变量的 Grunt for 循环

Grunt for-loop on grunt.task.run with variables

我目前正在尝试在 g运行t 中创建一个任务,多次向 运行 另一个任务发送参数。

这是我已经可以运行的单个构建任务:

var country = grunt.option('country') || 'X0';
var product = grunt.option('product') || 'Y0';
var subdomain = grunt.option('subdomain') || 'Z0';

grunt.registerTask('build_home', [
    'sprite:publicProduct',
    'sprite:home',
    'uglify:home',
    'sass:home',
    'csscomb:home',
    'cssmin:home'
]);

所以在我的日常工作中,我会运行命令:

grunt build_home --country=X0 --product=Y7 --subdomain=Z3

我现在想要的是一个 运行 我所有可能的预定义选项的任务:

grunt build_home_all

会是这样的:

grunt.registerTask('build_home_all', function() {

    var products = ['Y0','Y1','Y2','Y3','Y4','Y5','Y6','Y7','Y8','Y9'];
    var subdomains = ['Z0','Z1','Z2'];

    for (i = 0; i < products.length; i++) { 
        for (j = 0; j < subdomains.length; j++) {
            grunt.task.run('build_home --product='+products[i]+' --subdomain='+subdomains[j]);
        };
    };

    grunt.log.ok(['Finished.']);

});

我已经用 grunt.util.spawn 实现了这一点,但它有点 运行 异步并迫使我的 cpu 处理各种任务 运行同时.

当使用 grunt.task.run 调用任务的方法时,您将无法像通常使用 CLI 那样传递参数,但您仍然可以使用冒号分隔的表示法传递参数:
build_home --country=X0 --product=Y7 --subdomain=Z3 => build_home:X0:Y7:Z3

将您的 build_home_all 任务更新为以下内容:

function buildHomeAll() = {
    var products = ['Y0','Y1','Y2','Y3','Y4','Y5','Y6','Y7','Y8','Y9'],
        subdomains = ['Z0','Z1','Z2'],
        tasks = [],
        country = grunt.option('country') || 'X0';


    for (i = 0; i < products.length; i++) {
        for (j = 0; j < subdomains.length; j++) {
            tasks.push(['build_home',country, products[i],'subdomains[j]'].join(':'));
        };
    };
    grunt.task.run(tasks);

    grunt.log.ok(['Finished.']);
}

您将使用 grunt build_home_all --country=X0

调用此函数

接下来,您需要修改 build_home 任务以考虑可以传入参数的新方式:

function buildHome() = {
    if (!grunt.option('country') {
        grunt.option('country', this.args[0] || 'X0');
    })
    if (!grunt.option('product') {
        grunt.option('product', this.args[1] || 'Y0');
    })
    if (!grunt.option('subdomain') {
        grunt.option('subdomain', this.args[2] || 'Z0');
    })

    grunt.task.run([
        'sprite:publicProduct',
        'sprite:home',
        'uglify:home',
        'sass:home',
        'csscomb:home',
        'cssmin:home'
    ]);

最后,在您的 gruntfile.js:

中公开函数
grunt.registerTask('build_home', buildHome);
grunt.registerTask('build_home_all', buildHomeAll);