Gulp and Browserify - Hooking up Watchify

Shane Osbourne
InstructorShane Osbourne

Share this video with your friends

Send Tweet
Published 8 years ago
Updated 4 years ago

Beginning with a single Gulp task capable of generating a one-time Browserify bundle, we enable file-watching and incremental rebuilds by incorporating Watchify. We add a second task watch & refactor our initial code to enable the bulk of it to be re-used. We’ll look at exactly how to ‘wire’ these tools together and how the relationship between Watchify & Browserify can manifest into a seriously efficient workflow.

[00:01] Let's take the simple Gulp and Browserify setup that has a single entry point here and write the bundle to a dist directory here, and add to it file watching and incremental rebuilds. We can do that by using a library by the same authors, Browserify, called Watchify. So NPM install Watchify, and we'll bring it into our Gulp file. We'll create another task called watch. We want to reuse the bulk of this code here. But we don't want to lose the ability to call this js task independently.

[00:54] So we'll pull this out of here, and create another function called bundle. But instead of calling Browserify here, instead we'll pass it in as a parameter so that back in our js task, we can simply call bundle and then create the Browserify instance as we did before. We can check this still works by running Gulp.js and it does. Now that we've extracted this functionality into a function here, we can reuse that with Watchify.

[01:39] We'll create a watcher by calling Watchify and passing along a Browserify instance, that's how Watchify works, it wraps Browserify. Only this time as a second parameter, we pass along some properties that are exposed to us on the Watchify module. This is the section that allows the caching and incremental rebuilds within Browserify. Note that it's the second parameter to Browserify, not Watchify.

[02:14] To kick things off now that we have our watcher, we call the bundle function first, and pass it along as the bundler. This is so that Watchify knows which files are used in the bundle, and can begin watching them. Once running, we can listen to events that are emitted when files change. One of them is called update. This is called whenever a file that is used in the bundle has changed, so it's a perfect time to call bundle again and pass along our watcher.

[02:50] We can also listen to another event called log. We pass it straight along to gulp-util.log. This will output bundle information to the console every time a file changes. So now if we run gulp watch, you can see that it tells us how many bytes have been written in how long, and the process is still running. So now we can go back into our code, make a change, hit save, and you can see that the bundle is regenerated and it gives you the times as well.