2

Im trying to generate my gulp tasks instead of statically writing them .I would like to loop through an array and generate gulp tasks based on the item in the array.

Something like this , any help will be appreciated !

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'));
  })
})
2
  • 3
    This looks reasonable to me. What is the problem? Commented May 9, 2017 at 22:02
  • Sorry i tried with a for loop previously which didnt work. This does seem to work. Thanks :) Commented May 10, 2017 at 10:01

1 Answer 1

2

It is a closure issue. The problem is that the variable references within that function you are passing to gulp.task() in your case 'brand' should be different from the variable in

gulp.task(OtherVariableNameThanBrand, [brand, 'scripts']);

A solution for that is :

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);

For more details read about closure

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.