how to output multiple bundles with browserify and gulp

Brian FitzGerald picture Brian FitzGerald · May 23, 2014 · Viewed 16.4k times · Source

I have browserify bundling up files and it's working great. But what if I need to generate multiple bundles?

I would like to end up with dist/appBundle.js and dist/publicBundle.js

gulp.task("js", function(){

    return browserify([
            "./js/app.js",
            "./js/public.js"
        ])
        .bundle()
        .pipe(source("bundle.js"))
        .pipe(gulp.dest("./dist"));

});

Obviously this isn't going to work since I am only specifying one output (bundle.js). I can accomplish this by repeating the above statement like so (but it doesn't feel right, because of the repetition):

gulp.task("js", function(){

    browserify([
            "./js/app.js"
        ])
        .bundle()
        .pipe(source("appBundle.js"))
        .pipe(gulp.dest("./dist"));


    browserify([
            "./js/public.js"
        ])
        .bundle()
        .pipe(source("publicBundle.js"))
        .pipe(gulp.dest("./dist"));

});

Is there a better way to tackle this? Thanks!

Answer

urban_raccoons picture urban_raccoons · May 23, 2014

I don't have a good environment to test this in right now, but my guess is that it would look something like:

gulp.task("js", function(){
    var destDir = "./dist";

    return browserify([
        "./js/app.js",
        "./js/public.js"
    ])
        .bundle()
        .pipe(source("appBundle.js"))
        .pipe(gulp.dest(destDir))
        .pipe(rename("publicBundle.js"))
        .pipe(gulp.dest(destDir));

});

EDIT: I just realized I mis-read the question, there should be two separate bundles coming from two separate .js files. In light of that, the best alternative I can think of looks like:

gulp.task("js", function(){
    var destDir = "./dist";

    var bundleThis = function(srcArray) {
        _.each(srcArray, function(source) {
            var bundle = browserify(["./js/" + source + ".js"]).bundle();
            bundle.pipe(source(source + "Bundle.js"))
                  .pipe(gulp.dest(destDir));
        });
    };

    bundleThis(["app", "public"]);
});