Search code examples
node.jsnpmbowergulpbrowserify

How to use Gulp to create a separate vendor bundle with Browserify from Bower components


I'm using Gulp and Browserify to package my Javascript into 2 separate bundles: application.js and vendor.js.

How do I bundle the vendor package if my vendor libraries are installed with Bower?

In my gulpfile, I'm using the following modules:

var gulp = require("gulp");
var browserify = require("browserify");
var debowerify = require("debowerify");
var source = require("vinyl-source-stream");

Assuming that I have only the Phaser framework installed with bower (for this example), my Gulp task to create the application package looks like this:

gulp.task("scripts-app", function () {
  browserify("./app/javascripts/index.js")
    .external("phaser")
    .pipe(source("application.js"))
    .pipe(gulp.dest("./tmp/assets"));
});

Meanwhile, the vendor task looks like this:

gulp.task("scripts-vendor", function () {
  browserify()
    .transform(debowerify)
    .require("phaser")
    .pipe(source("vendor.js"))
    .pipe(gulp.dest("./tmp/assets"));
});

When I run this Gulp task, I get an error that states Error: Cannot find module 'phaser' from and then all the directories it search through (none of which are the bower_components directory).

Any ideas about how to package these up successfully are greatly appreciated. Thanks!


Solution

  • Answered my own question:

    When using require in the Gulp task, you need to supply a path to a file, not just a name.

    gulp.task("scripts-vendor", function () {
      browserify()
        .transform(debowerify)
        .require("./bower_components/phaser/phaser.js")
        .pipe(source("vendor.js"))
        .pipe(gulp.dest("./tmp/assets"));
    });
    

    Notice that require("phaser") became require("./bower_components/phaser/phaser.js").

    Doing this works, although the bundle takes forever to build (around 20 seconds). You're probably better of just loading giant libraries/frameworks directly into your app through a <script> tag and then using Browserify Shim.

    This let's you require() (in the NodeJS/Browserify sense) global variables (documentation).