循环遍历数组并生成Gulp任务

时间:2017-05-09 21:58:40

标签: javascript arrays node.js gulp

我试图生成我的gulp任务而不是静态编写它们。我想循环遍历数组并根据数组中的项生成gulp任务。

像这样的东西,任何帮助都将不胜感激!

var brands  = ['google','facebook','twitter']


brands.forEach(function (brand) {
  gulp.task(brand, function() {
    return gulp.src('./'+ brand + '.scss')
       .pipe(rename('var.scss'))
       .pipe(gulp.dest('./styles/tmp'));
  })
})

1 个答案:

答案 0 :(得分:0)

这是关闭问题。问题在于,在您的案例“品牌”中,您要传递给gulp.task()的该函数中的变量引用应该与

中的变量不同
gulp.task(OtherVariableNameThanBrand, [brand, 'scripts']);

一个解决方案是:

var brands  = ['google','facebook','twitter'];
var style = 'style-';
var styleBrands =[];

brands.forEach(function (brand) {
  gulp.task(brand, function() {
    return gulp.src('./'+ brand + '.scss')
        .pipe(rename('var.scss'))
        .pipe(gulp.dest('./styles/tmp'));
  })
});

brands.forEach(function(brand) {
  gulp.task(style + brand, [brand, 'scripts']);
  styleBrands.push(style + brand);
});

gulp.task('default', styleBrands);

有关更多详细信息,请参见closure