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.
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...
return gulp.src(...).pipe(gulp.dest(...));
note the return value is a stream because gulp.src and .pipe return streams.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);
});
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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With