12

There are several tasks defined with gulp.task in gulpfile.js:

gulp.task('sync-task', () => { ... });
gulp.task('async-task', cb => { ... });

I would like to start one of them programmatically. Preferably in the same process (no exec, etc.), because one of the reasons behind this is the ability to run the script in debugger.

How can this be done?

It looks like there were things like gulp.run and gulp.start, but they are deprecated in Gulp 4.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565

3 Answers3

14

It appears that a task can be retrieved with gulp.task getter function and called directly:

gulp.task('sync-task')();
gulp.task('async-or-random-task')(function callbackForAsyncTasks(err) {
  if (err)
    console.error('error', err);
});
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • @Daniel The answer took release version of Gulp 4 into account. It works on Gulp 4.0.0, as long as these tasks were defined previously before as `gulp.task('sync-task', () => {...})`. – Estus Flask Mar 21 '19 at 12:00
  • Ok, I think the answers would benefit from code that would do just that so that is clear... – Daniel Mar 22 '19 at 12:42
  • 1
    This works, however, I'm not getting console output like when executing the task through gulp. I would expect `[12:00:00] Starting 'sync-task'...` and `[12:00:01] Finished 'sync-task' after 1000 ms` to be outputted, but I'm not getting that. Is this still possible, if yes, how? – Creative Jul 11 '19 at 09:46
12

Adding to the accepted answer:

Yes you can retrieve a task by calling gulp.task, but rather than calling it directly you can wrap it in a call to gulp.series (presumably gulp.parallel would also work) and call that. This has the benefit of producing the expected "Starting/Finished" output. An example would be:

gulp.series(gulp.task('some-task'))();

with the output:

[09:18:32] Starting 'some-task'...
[09:18:32] Finished 'some-task' after 7.96 ms

This was tested just now on gulp v4.0.2.

tuck182
  • 121
  • 2
  • 4
  • Thanks, this answers [this comment](https://stackoverflow.com/questions/42258908/run-gulp-4-task-programmatically/57629982#comment100507229_42259368) which I've missed. – Estus Flask Aug 23 '19 at 16:47
0

I can run a task by doing this:

gulp.task('sync-task').unwrap()();
  • the `the gulp.task('sync-task').unwrap()` returns the original task function But it is not called as Gulp task function (synchronous call only), the easiest way to grammatically call Gulp tasks is to use the `parallel(task1, ...)()` or `series(task1, ...)()` methods (from Gulp: v4.0.0 the `task()` method is discouraged to use (but supported)) – Pall Arpad Jan 14 '20 at 13:12