How to save a stream into multiple destinations with Gulp.js?

Javascriptnode.jsBrowserifyGulp

Javascript Problem Overview


const gulp = require('gulp');
const $ = require('gulp-load-plugins')();
const source = require('vinyl-source-stream');
const browserify = require('browserify');

gulp.task('build', () =>
  browserify('./src/app.js').bundle()
    .pipe(source('app.js'))
    .pipe(gulp.dest('./build'))       // OK. app.js is saved.
    .pipe($.rename('app.min.js'))
    .pipe($.streamify($.uglify())
    .pipe(gulp.dest('./build'))       // Fail. app.min.js is not saved.
);

Piping to multiple destinations when file.contents is a stream is not currently supported. What is a workaround for this problem?

Javascript Solutions


Solution 1 - Javascript

Currently you have to use two streams for each dest when using file.contents as a stream. This will probably be fixed in the future.

var gulp       = require('gulp');
var rename     = require('gulp-rename');
var streamify  = require('gulp-streamify');
var uglify     = require('gulp-uglify');
var source     = require('vinyl-source-stream');
var browserify = require('browserify');
var es         = require('event-stream');

gulp.task('scripts', function () {
    var normal = browserify('./src/index.js').bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('./dist'));

    var min = browserify('./src/index.js').bundle()
        .pipe(rename('bundle.min.js'))
        .pipe(streamify(uglify())
        .pipe(gulp.dest('./dist'));

    return es.concat(normal, min);
});

EDIT: This bug is now fixed in gulp. The code in your original post should work fine.

Solution 2 - Javascript

I was facing similar issue and wanted the gulp source to be copied to multiple locations after lint, uglify and minify tasks. I ended up resolving this as below,

gulp.task('script', function() {
  return gulp.src(jsFilesSrc)
    // lint command
    // uglify and minify commands
    .pipe(concat('all.min.js'))
    .pipe(gulp.dest('build/js')) // <- Destination to one location
    .pipe(gulp.dest('../../target/build/js')) // <- Destination to another location
});

Solution 3 - Javascript

For the case of broadcasting updates to multiple destinations, looping the gulp.dest command over an array of destinations works well.

var gulp = require('gulp');

var source = './**/*';

var destinations = [
    '../foo/dest1',
    '../bar/dest2'
];

gulp.task('watch', function() {
    gulp.watch(source, ['sync']);
});

gulp.task('sync', function (cb) {
    var pipeLine = gulp.src(source);

    destinations.forEach(function (d) {
        pipeLine = pipeLine.pipe(gulp.dest(d));
    });

    return pipeLine;
});

Solution 4 - Javascript

I think this way is easier. Justo you have two destination, but before minify plugin you put one path to the normal file and the you put the minify plugin follow the path that you want to have a minify file.

for example:

gulp.task('styles', function() {

    return gulp.src('scss/main.scss')
    .pipe(sass())
    .pipe(gulp.dest('css')) // Dev normal CSS
    .pipe(minifycss())
    .pipe(gulp.dest('public_html/css')); // Live Minify CSS

});

Solution 5 - Javascript

I've had a lot of the same problem with Gulp, for various tasks piping to multiple destinations seems difficult or potentially impossible. Also, setting up multiple streams for one task seems inefficient but I guess this is the solution for now.

For my current project I needed multiple bundles to be associated with various pages. Modifying the Gulp Starter

https://github.com/greypants/gulp-starter

browserify/watchify task:

https://github.com/dtothefp/gulp-assemble-browserify/blob/master/gulp/tasks/browserify.js

I used a forEach loop inside of the glob module callback:

gulp.task('browserify', function() {

  var bundleMethod = global.isWatching ? watchify : browserify;

  var bundle = function(filePath, index) {
    var splitPath = filePath.split('/');
    var bundler = bundleMethod({
      // Specify the entry point of your app
      entries: [filePath],
      // Add file extentions to make optional in your requires
      extensions: ['.coffee', '.hbs', '.html'],
      // Enable source maps!
      debug: true
    });

    if( index === 0 ) {
      // Log when bundling starts
      bundleLogger.start();
    }

    bundler
      .transform(partialify)
      //.transform(stringify(['.html']))
      .bundle()
      // Report compile errors
      .on('error', handleErrors)
      // Use vinyl-source-stream to make the
      // stream gulp compatible. Specifiy the
      // desired output filename here.
      .pipe(source( splitPath[splitPath.length - 1] ))
      // Specify the output destination
      .pipe(gulp.dest('./build/js/pages'));

    if( index === (files.length - 1) ) {
      // Log when bundling completes!
      bundler.on('end', bundleLogger.end);
    }

    if(global.isWatching) {
      // Rebundle with watchify on changes.
      bundler.on('update', function(changedFiles) {
        // Passes an array of changed file paths
        changedFiles.forEach(function(filePath, index) {
          bundle(filePath, index);
        });
      });
    }
  }

  // Use globbing to create multiple bundles
  var files = glob('src/js/pages/*.js', function(err, files) {
    files.forEach(function(file, index) {
      bundle(process.cwd() + '/' + file, index);
    })
  });

});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKonstantin TarkusView Question on Stackoverflow
Solution 1 - JavascriptContraView Answer on Stackoverflow
Solution 2 - JavascriptAnmol SarafView Answer on Stackoverflow
Solution 3 - JavascriptdavidmdemView Answer on Stackoverflow
Solution 4 - JavascriptLuis ChiappeView Answer on Stackoverflow
Solution 5 - JavascriptdtothefpView Answer on Stackoverflow