Search code examples
javascriptsvgforeachgulppromise

Add Promise to gulp task with forEach


I have a svg-sprites gulp task looping through my Sprites. Some of them need to be minified, so I have an if running the minify task on those sprites.

I'd like it to show as finished when the forEach is finished. Right now it says "Finished" way too early. I guess I should add a promise, but I am not sure how to approach it. Help appreciated.

var gulp =        require('gulp');
var svgSprite =   require('gulp-svg-sprite');
var svgmin =      require('gulp-svgmin');

gulp.task('svg-sprites', function() {

  var stream = '';

  config.svgSprites.forEach(function (item) {

    stream = gulp.src(item.src + '/**/*.svg');

    if(item.doMinify) {
      stream.pipe(svgmin({
        plugins: [
          {
            removeAttrs: {
              attrs: ['path:fill', 'g:fill']
            }
          }
        ]
      }))
    }

    stream.pipe(svgSprite())
      .pipe(gulp.dest(normalizePath(item.dest)));
  });

  return stream;
});

Solution

  • I apparently needed to push my streams to an array of streams and merging all streams at the end, all the time "updating" my stream variable when piping. I ended up with this:

    var gulp =        require('gulp');
    var svgSprite =   require('gulp-svg-sprite');
    var svgmin =      require('gulp-svgmin');
    var merge =       require('merge-stream');
    
    gulp.task('svg-sprites', function() {
      var streams = [];
    
      config.svgSprites.forEach(function (item) {
        var stream = gulp.src(item.src + '/**/*.svg');
    
        if(item.doMinify) {
          // "Update" stream to be a reference to the output of the task
          stream = stream.pipe(svgmin({
            plugins: [
              {
                removeAttrs: {
                  attrs: ['path:fill', 'g:fill']
                }
              }
            ]
          }))
        }
    
        // "Update" stream to be a reference to the output of the task
        stream = stream.pipe(svgSprite()).pipe(gulp.dest(normalizePath(item.dest)));
    
        streams.push(stream);
      });
    
      return merge.apply(this, streams);
    });