Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gulp Bundle + Browserify on multiple files

So I have asimple gulp task function which currently converts my main.jsx to a main.js file:

gulp.task("bundle", function () {
    return browserify({
        entries: "./app/main.jsx",
        debug: true
    }).transform(reactify)
        .bundle()
        .pipe(source("main.js"))
        .pipe(gulp.dest("app/dist"))
});

I was wondering if it would be possible to put multiple bundles in this gulp.task? My ideal outcome would be being able to do:

  • main.jsx to main.js

  • otherPage.jsx to otherPage.js

  • otherPage2.jsx to otherPage2.js

All in one gulp task.

I have searched onliine but cannot seem to find anything relevant, any help or advice is appreciated, thank you in advance.

like image 262
holodan Avatar asked Oct 26 '16 23:10

holodan


1 Answers

If you want to create a bundle for each file you need to loop over the respective files, create a stream for each file and then merge the streams afterwards (using merge-stream):

var merge = require('merge-stream');

gulp.task("bundle", function () {
  var files = [ "main", "otherPage", "otherPage2" ];
  return merge(files.map(function(file) {
    return browserify({
        entries: "./app/" + file + ".jsx",
        debug: true
    }).transform(reactify)
        .bundle()
        .pipe(source(file + ".js"))
        .pipe(gulp.dest("app/dist"))
  }));
});

The above requires that you maintain a list of files manually as an array. It's also possible to write a task that bundles all .jsx files in the app directory without having to maintain an explicit array of the files. You just need the glob package to determine the array of files for you:

var merge = require('merge-stream');
var glob = require('glob');
var path = require('path');

gulp.task("bundle", function () {
  var files = glob.sync('./app/*.jsx');
  return merge(files.map(function(file) {
    return browserify({
        entries: file,
        debug: true
    }).transform(reactify)
        .bundle()
        .pipe(source(path.basename(file, '.jsx') + ".js"))
        .pipe(gulp.dest("app/dist"))
  }));
});
like image 104
Sven Schoenung Avatar answered Oct 23 '22 05:10

Sven Schoenung