Sitemap
wehavefaces

software engineer | open-source buccaneer | aphrostysicist

gulp + browserify, the gulp-y way

7 min readAug 14, 2014

--

Or How I Learned To Stop Worrying About gulp-browserify (and other gulp-* wrapper plugins) And Love Vanilla NodeJS Modules

Updates as of 20 March 2016: The information in this article has been outdated for some time, and I have since moved away from Gulp to Webpack for bundling and packaging NodeJS source for browser. (I’m not knocking on Gulp here, it is still a great library. Just that I think Webpack works well in my case).

Seems that having gulp + browserify is still a concern for a lot of Gulp users, so, if anyone has a better solution to packaging your NodeJS source for browser and would like to share it with everyone else, feel free to ping me and I’ll put up a link :)

—

tl;dr

gulp-browserify was blacklisted; here’s how you can port your ol` recipe from gulp-browserify to vanilla browserify:

Here’s the forbidden recipe using gulp-browserify:

var gulp = require(‘gulp’);
var browserify = require(‘gulp-browserify’);
var uglify = require(‘gulp-uglify’);
gulp.task(‘browserify’, function () {
return gulp.src([‘./src/*.js’])
.pipe(browserify())
.pipe(uglify())
.pipe(gulp.dest(‘./dist’));
});

And here’s the recipe replacing gulp-browserify with browserify + vinyl-transform

var gulp = require('gulp');
var browserify = require('browserify');
var transform = require('vinyl-transform');
var uglify = require('gulp-uglify');

gulp.task('browserify', function () {
var browserified = transform(function(filename) {
var b = browserify(filename);
return b.bundle();
});

return gulp.src(['./src/*.js'])
.pipe(browserified)
.pipe(uglify())
.pipe(gulp.dest('./dist'));
});

Easy-peasy, lemon-squeezy.

You can simply take that and start using browserify in your gulp recipes easily.

Read on if you want more details on what’s this fuss is all about and why this works out.

61 reasons not to use gulp-browserify (and counting)

The main browserify library has enough open issues at the moment (61 open issues as of 14 Aug 2014) that it makes hard to guarantee that gulp plugin that is a wrapper around browserify will always be up-to-date.

In fact, since 13 March 2014, the maintainer of gulp-browserify has stopped updating the codebase after being blacklisted by gulpjs.

How different would it be to use browserify than gulp-browserify?

Not much, really. We only need vinyl-transform to make this all work, which is still a useful library for your other gulp needs.

Using gulp-browserify

var gulp = require(‘gulp’);
var browserify = require(‘gulp-browserify’);
gulp.task(‘browserify’, function () {
return gulp.src([‘./src/*.js’])
.pipe(browserify())
.pipe(gulp.dest(‘./dist’));
});

Using browserify + vinyl-transform

var gulp = require(‘gulp’);
var browserify = require(‘browserify’);
var transform = require(‘vinyl-transform’);
gulp.task(‘browserify’, function () {
var browserified = transform(function(filename) {
var b = browserify(filename);
return b.bundle();
});
return gulp.src(['./src/*.js'])
.pipe(browserified)
.pipe(gulp.dest('./dist'));
});

That wasn’t so bad, eh?

How about the pre- and post-bundle events emitted by gulp-browserify?
Those are really useful!

Firstly, browserify already emits its own events by itself, of which it is not clear if gulp-browserify supports as well.

Instead, it adds on two additional events that are not supported by the main library (prebundle and postbundle).

Nonetheless, you can still achieve the same with the original browserify APIs:

...
gulp.task(‘browserify’, function () {
var browserified = transform(function(filename) {
var b = browserify(filename);
// pre-bundle actions here
// for eg: transform()
b.transform(reactify)
…
return b.bundle();
});
return gulp.src(['./src/*.js'])
.pipe(browserified)
// post-bundle actions here
// for e.g.: uglify() after bundling
.pipe(uglify());
.pipe(gulp.dest('./dist'));
});

With this, we maintain both the gulp-way and browserify-way.

We can still use the idioms for browserify here for other non-gulp projects.

Much excellent.

Comprehensive browserify API documentation

One great benefit that comes with using the original browserify is the excellent API documentation.

Go ahead and bookmark that.

How about vinyl-source-stream?

If you’ve been shopping around for gulp recipes for browserify, you’d probably would have stumbled upon recipes using vinyl-source-stream, like so:

var gulp = require(‘gulp’);
var browserify = require(‘browserify’);
var source = require(‘vinyl-source-stream’);
…
gulp.task(‘browserify’, function () {
return browserify(‘./src/main.js’)
.bundle().
.pipe(source(‘output.js’))
.pipe(gulp.dest(‘./dist’));
});

This works perfectly as it is and it works for most cases, except when:

  • you want to specify a glob pattern and browserify multiple files instead of one file at a time, for eg: ‘./src/**/*.js’ (unsurprisingly a common use-case)
  • you want to apply more transformation post-bundle (after source())

So what can you do?

For the first case, you might be able to get away with processing multiple files by doing the following using glob: (25 March 2015: Removed dependency on lodash, thanks to @veryfizzyjelly / Matt Styles)

var gulp = require(‘gulp’);
var browserify = require(‘browserify’);
var source = require(‘vinyl-source-stream’);
var glob = require(‘node-glob’);
gulp.task(‘browserify’, function (cb) {
glob(‘./src/**/*.js, {}, function (err, files) {
var b = browserify();
files.forEach(function (file) {
b.add(file);
});
b.bundle().
.pipe(source(‘output.js’))
.pipe(gulp.dest(‘./dist’));
cb();
});
});

This is okay, but not quite gulp-y.

Secondly, you might want to uglify the resulting bundle with gulp-uglify, for example.

Get Hafiz Ismail’s stories in your inbox

Join Medium for free to get updates from this writer.

Except this does not work as well as expected when you try to run it.

var gulp = require(‘gulp’);
var browserify = require(‘browserify’);
var source = require(‘vinyl-source-stream’);
var glob = require(‘node-glob’);
var uglify = require(‘gulp-uglify’);
gulp.task(‘browserify’, function (cb) {
glob(‘./src/**/*.js, {}, function (err, files) {
var b = browserify();
files.forEach(function (file) {
b.add(file);
});
b.bundle().
.pipe(source(‘output.js’))
.pipe(uglify())
.pipe(gulp.dest(‘./dist’));
cb();
});
});

Running gulp will spit the following error

Error in plugin ‘gulp-uglify’
Streaming not supported

So what’s happening here?

Some gulp-* plugins works by taking in buffered vinyl files objects as input. But vinyl-source-stream emits a streaming vinyl file object.

That’s where vinyl-buffer comes in. So we simply need to convert that to a buffered vinyl by using vinyl-buffer, like so

var gulp = require(‘gulp’);
var browserify = require(‘browserify’);
var source = require(‘vinyl-source-stream’);
var buffer = require(‘vinyl-buffer’);
var glob = require(‘node-glob’);
var uglify = require(‘gulp-uglify’);
gulp.task(‘browserify’, function (cb) {
glob(‘./src/**/*.js, {}, function (err, files) {
var b = browserify();
files.forEach(function (file) {
b.add(file);
});
b.bundle().
.pipe(source(‘output.js’))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest(‘./dist’));
cb();
});
});

Okay, so now we have a working recipe, but having to use glob module seems clunky and not very gulp-y.

We already missed not having gulp.src() around with its glob patterns for specifying file inputs.

Let’s see what we can do about that.

Replace vinyl-source-stream + vinyl-buffer with vinyl-transform
and get rewarded something extra!

vinyl-transform is another excellent library written by the same guy who wrote vinyl-source-stream and vinyl-buffer.

Here is the recipe to achieve the same result with vinyl-transform:

var gulp = require(‘gulp’);
var browserify = require(‘browserify’);
var transform = require(‘vinyl-transform’);
var uglify = require(‘gulp-uglify’);
gulp.task(‘browserify’, function () {
var browserified = transform(function(filename) {
var b = browserify(filename);
return b.bundle();
});
// hello gulp.src() my old friend
return gulp.src([‘./src/**/*.js’])
.pipe(browserified)
.pipe(uglify())
.pipe(gulp.dest(‘./dist’));
});

Now ain’t that purdy?

We managed to removed dependencies on vinyl-source-stream and vinyl-buffer, with glob.

We now have something concise and we have our old friend, gulp.src() back in action.

What kind of voodoo magickery is this vinyl-transform?

A little bit of background: with all the hype around gulpjs about it being a streaming build, the streams in a gulp pipeline aren’t just regular NodeJS Stream class which normally operate on Strings and Buffers exclusivly.

Instead, gulp streams operates in object-mode which emits vinyl file objects.

So, if we want to pipe a regular Stream, for example, from browserify.bundle(), into a gulp pipe, we simply need to convert the regular text/buffer Stream to a vinyl file object

To further complicate stuff, vinyl file object’s content works on 3 forms:

  • Stream
  • Buffer
  • Empty

And that’s exactly what vinyl-transform is for; it wraps around a regular text Stream and gives you a vinyl file object that you can push into a gulp pipe.

As something extra, it takes care of both streaming and buffered vinyl file object. Win.

You can apply the same principles to other existing npm modules that supports regular Stream to make them compatible with gulp.

So, what exactly are vinyl file objects?

Currently, there isn’t much to the documentation on vinyl and gulp’s design decision in using those over regular Stream.

Updated on 12 Nov 2014: Found an article written by one of the lead contributors to gulp (Eric Schoffstall / @contra) that provides some insight on vinyl and its role in gulp.

Hopefully, as the ecosystem mature, we get better documentation on it (sooner than later).

For now, here are some references on vinyl:

Where do we go from here?

This little article (that went on far too long) may try to demonstrate how one can move away from using gulp-browserify and all that, but the same principles can be applied for using other existing npm-managed modules in your gulp recipes.

Some wrapper plugins may provide some syntactic convenience by shaving off 2–3 lines from your recipe file but at what cost?

Personally, I’d say vanilla NodeJS modules over wrapper plugins.

Maybe all this boils down to personal preference, but probably it’s better for the gulp ecosystem not to be flooded with wrapper plugins that are poorly documented, adds to the maintenance cost and introduces more technical complexity rather than reduces it.

Now, have a cookie.

Updates:

  1. 12 Nov 2014: Added link to article written by @contra: Gulp: The vision, history and future of the project
  2. 25 Mar 2015: Removed dependency from lodash. Thanks to @veryfizzyjelly
  3. 25 Mar 2015: @asafkatz had created a PR to update gulpjs’ recommended recipe for browserify + uglify2 with sourcemaps (common use-case) and has since been merged into the main repo.
Hafiz Ismail
Hafiz Ismail

Written by Hafiz Ismail

aphrostysicist (æf.rəʊ ˈstɪz.ɪ.sɪst) : noun - someone who is not an astrophysicist | @sogko

wehavefaces
wehavefaces

Published in wehavefaces

software engineer | open-source buccaneer | aphrostysicist