Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create repeating pipe in gulp?

I have a gulp task to inject several dependencies in index.html as this :

return gulp.src(config.serve.html)
          .pipe($.inject(gulp.src(prependSource(config.inject.source.indexes)), {
            read: false,
            starttag: config.inject.indexes,
            addRootSlash: false,
            addPrefix: prefix,
            ignorePath: ignore
          }))
          .pipe($.inject(gulp.src(managerList), {
            read: false,
            starttag: config.inject.managers,
            addRootSlash: false,
            addPrefix: prefix,
            ignorePath: ignore
          }))
          .pipe($.inject(gulp.src(prependSource(config.inject.source.directives)), {
            read: false,
            starttag: config.inject.directives,
            addRootSlash: false,
            addPrefix: prefix,
            ignorePath: ignore
          }))

          .pipe($.inject(gulp.src(prependSource(config.inject.source.routes)), {
            read: false,
            starttag: config.inject.routes,
            addRootSlash: false,
            addPrefix: prefix,
            ignorePath: ignore
          }))
          .pipe($.inject(gulp.src(prependSource(config.inject.source.css)), {
            read: false,
            starttag: config.inject.css,
            addRootSlash: false,
            addPrefix: prefix,
            ignorePath: ignore
          }))


          .pipe($.size())
          .pipe(gulp.dest(dest));
};

As you can see, all the pipes are in repeating in some fashion (except the managerList). So what I want is to consolidate the repeating pipes into one single pipe, with the help of an array of injects. How to achieve the same?

like image 493
Koustuv Sinha Avatar asked Feb 11 '23 01:02

Koustuv Sinha


1 Answers

gulp.src returns a stream (as does each .pipe). If you think about what each .pipe call is doing, you can simply turn it into a for loop. Something like this:

config = { /* your config object */ };

var stream = gulp.src(/* source glob */);
for (var i = 0; i < injects.length; i++) {
  stream = stream.pipe($.inject(gulp.src(prependSource(config.inject.source[i])), config.inject.starttag[i]));
}

stream.pipe($.size())
      .pipe(gulp.dest(dest));

return stream;
like image 74
Akshay Dhalwala Avatar answered Feb 13 '23 14:02

Akshay Dhalwala