是否可以在属性中使用Grunt任务目标名称?

时间:2014-05-28 18:28:01

标签: javascript gruntjs task

我使用grunt-replace任务替换index.html文件中的一些内容。但我希望尽可能避免代码重复。以下代码段无法正常工作,但它是我尝试实现的一个示例:

replace: {
    options: {
        patterns: [
            {
                match: /<(script.*?src=)"(?![\w/]+environment)/g,
                replacement: '<$1"//<%= config.cdn[target] %>/'
            }
        ]
    },
    a: {
        files: [
            {
                src: '<%= config.path.dist.output %>/index.html',
                dest: '<%= config.path.dist.output %>/index-a.html'
            }
        ]
    },
    b: {
        files: [
            {
                src: '<%= config.path.dist.output %>/index.html',
                dest: '<%= config.path.dist.output %>/index-b.html'
            }
        ]
    }
}

当我致电replace:a时,我希望替换模式来自config.cdn['a'],当我致电replace:b时,我希望替换模式来自config.cdn['b']

这可能吗?

1 个答案:

答案 0 :(得分:1)

这可能有点难看,但它可以起作用或者至少有点帮助:

replace: (function () {

    var exports = {},
        targets = ['a', 'b'],
        target,
        i,
        j;

    for (i = 0, j = targets.length; i < j; i++) {
        target = targets[i];

        exports[target] = {
            options: {
                patterns: [
                    {
                        match: /<(script.*?src=)"(?![\w/]+environment)/g,
                        replacement: '<$1"//' + config.cdn[target] + '/'
                    }
                ]
            },
            files: [
                {
                    src: config.path.dist.output + '/index.html',
                    dest: config.path.dist.output + '/index-' + target + '.html'
                }
            ]
        }
    }

    return exports;

}())
相关问题