Conditionally run a task that does nothing in runSequence

130 Views Asked by At

I have a main task called build, in this task in dev mode, i want to run watchers.

During production I don't need to run any watchers,

gulp.task('build', cb => {
    return $.runSequence(
        'globals',
        'inline',   
        'lazy',
        (production ? ['empty'] : ['globals:watch', 'inline:watch', 'lazy:watch']),
        cb
    );
});

With runSequence i tried passing in false and null as a param but it still tries to treat it as a taskname.

So the solution I came up with was to run a task, that does nothing:

gulp.task('empty', cb => {
    return cb();
});

Is this the right way? It seems to only work sometimes and I'm not really sure why.

Any help would be great

1

There are 1 best solutions below

0
On

I don't see why your solution should work only sometimes. There's nothing wrong with it, so unless your actual code is significantly different from what you've posted here you should be fine.

If you want to get rid of the empty task you can use .concat() to construct your task array and then apply() it to runSequence:

gulp.task('build', cb => {
    return $.runSequence.apply(null, [
        'globals', 
        'inline', 
        'lazy'
      ]
      .concat((production) ? [] : [['globals:watch', 'inline:watch', 'lazy:watch']])
      .concat(cb));
});

Probably the best solution however is to use the new ES6 spread operator. This requires that you have at least nodejs version 5.x installed, but it makes your task really short and readable:

gulp.task('build', cb => {
    return $.runSequence(
      'globals', 
      'inline', 
      'lazy',
      ...(production) ? [] : [['globals:watch', 'inline:watch', 'lazy:watch']],
      cb);
});