我使用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']
。
这可能吗?
答案 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;
}())