Versions used below
Why reusable pipelines?
A typical pattern for gulp tasks is
If some other task needs to run
stepC you could copy/paste the code or move it out into something reusable. The latter will result in a more maintainable build.
The manual way
Here’s a way to do it with no help from outside modules.
This works but it reads out of order – the call to
gulp.src is not first. In gulp builds I’m used to seeing code in the same order that the file processing happens in.
It looks worse when there are steps before the reusable pipeline.
Why pass inputStream in?
It seems like the previous examples could be cleaner by not passing
processJs. We could just use
processJs() directly in the gulp task.
This runs but it doesn’t give the desired effect.
In node streams
b. That means
processJs returns a
rev stream and
gulp.src will pipe directly into it. Even though
uglify is also piped into
rev, nothing pipes into
uglify so it has no effect.
Okay, on to some better ideas.
lazypipe creates a function that lazily creates your pipeline.
This is nicer because the code is in the same order as the file processing.
Passing parameters to gulp plugins
The previous code example uses
.pipe(uglify) instead of
.pipe(uglify()) because lazypipe will invoke
uglify for us when needed. We lost our chance to pass an options object to
.pipe() accepts extra parameters which are passed directly to the plugin.
Gotcha with gulp-if
With lazypipe it’s tricky to use streams that take other streams, e.g. gulp-if.
Common gulp-if usage looks like
If we do that when building the lazypipe it’s no longer lazy and no longer reusable. There is a way around that but this is more special case handling than I’d like in a build file.
stream-combiner2 wraps a series of streams into a single duplex stream.
Things to note:
care piped together inside
- Input to
wrapperis the input to
- Output of
cis the output of
- Errors from
cbecome errors of
With that in mind, we can do
This is my preferred approach for creating reusable pipelines in a gulp build.
bun works like stream-combiner2 except it takes an array of streams.