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.

3 Answers 3

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

@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', () => {...}).
Ok, I think the answers would benefit from code that would do just that so that is clear...
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?
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.

1 Comment

Thanks, this answers this comment which I've missed.
0

I can run a task by doing this:

gulp.task('sync-task').unwrap()();

1 Comment

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))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.