Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using del in gulp.series()

I try to clean folder before start tasks in gulp 4

var gulp = require('gulp');
var del = require('del');

gulp.task('clean', function() {
    del.sync('folder/*');
});

gulp.task('foo', gulp.series('clean', 'something'));

It doesn't work, because 'clean' task must return some stream. I've found workaround:

gulp.task('clean', function() {
    del.sync('folder/*');
    var emptyStream = gulp.src([]).pipe(gulp.dest('/'));
    return emptyStream;
});

, but still hope to find a better solution.

like image 903
vdshb Avatar asked Mar 27 '15 21:03

vdshb


1 Answers

gulp allows three options for managing asynchronicity. First, if a function completes (returns nothing/undefined, or a simple value) gulp considers the task done and moves on. However, if your task is an asynchronous task (as much is in node) then you...

  1. Return a stream. return gulp.src(...).pipe(gulp.dest(...)); note the return value is a stream because gulp.src and .pipe return streams.
  2. Return a Promise.
  3. Use a callback. if you place a variable in the function's argument then gulp will expect the callback to be called and wait for that to happen. Giving the callback a value as an argument is considered a failure and calling it without a value is considered a success.

In the case of del, it doesn't do the first two but takes a callback which it handles the same as in scenario 3 above.

gulp.task('clean', function(done) {
  del(['output'], done);
});

Examples

Here is an example of using a callback manually called with a stream:

gulp.task('foo', function(done) {
  gulp.src('input')
    .pipe(gulp.dest('output'))
    .on('end', function() {
      done();
    })
    .on('error', function(err) {
      done(err);
    });
});

Since streams are so common returning one will do the above for you. (Note the done was removed so gulp won't expect it to be called).

gulp.task('foo', function() {
  return gulp.src('input')
    .pipe(gulp.dest('output'));
});

Not everything can be a stream and call backs can be daunting to manage so you can instead return a promise:

gulp.task('foo', function() {
  return new Promise(function(resolve) {
    setTimeout(resolve, 5000);
  });
});
like image 160
Sukima Avatar answered Sep 19 '22 23:09

Sukima