任何在gulp任务完成时运行函数的方法

时间:2016-08-29 11:54:24

标签: javascript gulp

我的gulpfile中有很多gulp任务,我需要在每个任务完成后运行一个函数。

我像这样处理了我的任务注册:

var registerTask = function (taskName, dependencies, todo) {
  if (isProduction) {
    gulp.task(taskName, dependencies, todo);
  } else {
    var prefixedTaskName = '_' + taskName;

    // the original task registers here with another name
    gulp.task(prefixedTaskName, dependencies, todo);

    // register my task to do after the original task is done
    gulp.task(taskName, [prefixedTaskName], myRepeatedFunction);
  }
}

我按照这样注册我的任务:

registerTask('foo', [], function () {
  gulp
    .src()
    .pipe()
    ...
})

但是这会使我的终端弄脏日志(强调的任务名称):

[15:54:17] Using gulpfile ~/Projects/xxx/gulpfile.js
[15:54:17] Starting '_default'...
[15:54:17] Starting '_remove-source-map'...
[15:54:17] Starting '_fontastic'...
[15:54:28] Finished '_fontastic' after 11 s
[15:54:28] Starting 'fontastic'...
[15:54:28] Finished 'fontastic' after 125 μs
[15:54:28] Starting '_js-hint'...
[15:54:28] Finished '_remove-source-map' after 11 s
[15:54:28] Starting 'remove-source-map'...
[15:54:28] Finished 'remove-source-map' after 59 μs
[15:54:28] Starting '_sass'...
[15:54:33] Finished '_sass' after 4.19 s
[15:54:33] Starting 'sass'...
[15:54:33] Finished 'sass' after 21 μs
[15:54:33] Finished '_js-hint' after 5.11 s
[15:54:33] Starting 'js-hint'...
[15:54:33] Finished 'js-hint' after 18 μs
[15:54:33] Starting '_js'...
[15:54:50] Finished '_js' after 17 s
[15:54:50] Starting 'js'...
[15:54:50] Finished 'js' after 17 μs
[15:54:50] Finished '_default' after 32 s
[15:54:50] Starting 'default'...
[15:54:50] Finished 'default' after 19 ms

我正在寻找一种更好的方法来做同样的事情而没有脏日志(我不想使用--silent)

如果gulp.task中有回调,我可以用很好的方式做同样的事情。

1 个答案:

答案 0 :(得分:4)

Gulp从orchestrator继承其任务运行功能,提供.on()函数来注册事件监听器。

假设您有一个任务foo,并希望在任务foo完成后运行一个函数。你可以这样做:

var gulp = require('gulp');

gulp.task('foo', function() {
  // do task stuff
});

gulp.on('task_stop', function(evt) {
  if (evt.task == 'foo') {
    // do stuff after task foo has finished
  }
});

为此,您 以确保您的异步任务are properly signalling completion。这意味着不要忘记返回您的流或在异步任务中调用回调函数!