如何让 gulp 在完成之前不完成任务?

How to make gulp not finish task before it's done?

我有这个 gulp 任务,它工作正常,但是当查看日志时,它总是说开始任务,然后立即完成任务,然后开始记录所有内容。我如何让它等到一切都完成,直到它说完成?我认为这是由于函数是异步的,所以 done() 立即被调用,但我不确定该怎么做。

gulp函数

gulp.task("img-projects", function(done) {
  gulp.src('projects/*/images/**/*.*')
    .pipe(imagemin())
    .pipe(rename(function (path) {
        path.dirname = path.dirname.replace('/images','');
        console.log('path');
        return path;
    }))
    .pipe(gulp.dest('public'));

    done();
});

输出:

[19:11:55] Starting 'js-projects'...
[19:11:55] Finished 'js-projects' after 34 ms
[19:11:55] path
[19:11:55] path
[19:11:55] path

试试,

gulp 函数是异步的

gulp.task("img-projects", function() {
  return gulp.src('projects/*/images/**/*.*')
    .pipe(imagemin())
    .pipe(rename(function (path) {
        path.dirname = path.dirname.replace('/images','');
        console.log('path');
        return path;
    }))
    .pipe(gulp.dest('public'));
});

您只需添加一个 on('end', ...) 侦听器,等待 gulp 流完成后再调用 done():

gulp.task("img-projects", function(done) {
  gulp.src('projects/*/images/**/*.*')
    .pipe(imagemin())
    .pipe(rename(function (path) {
        path.dirname = path.dirname.replace('/images','');
        console.log('path');
        return path;
    }))
    .pipe(gulp.dest('public'))
    .on('end', done);
});

来源: How do you run a gulp "on end" task but only at the end of the current task?

gulp API(src()/dest()/等的文档):https://github.com/gulpjs/gulp/tree/master/docs/api

node.js 流 API 提供 on(...)https://nodejs.org/api/stream.html

类似问题:https://github.com/gulpjs/gulp/issues/1181#issuecomment-126694791