In my previous post Using Gulp with Browserify and Watchify - Updated, I presented a solution for setting Gulp with Browserify and Watchify using vinyl-source-stream. However, that method is no longer working as Browserify updated to version 8.0.2. This post will demonstrate a new updated solution that has been tested on Browserify 12.0.1 and Watchify 3.6.0.

# Structure

In my project, I will have to folder named js for containing all the source .js files and another folder called dist for outputing all the bundles after built.

├─┬ js
│ ├─┬ page1
│ │ ├── display.js
│ │ └── model.js
│ ├─┬ page2
│ │ └── controller.js
│ ├─┬ util
│ │ ├── validation.js
│ └── page1.js
│ └── page2.js
├── dist
└── gulpfile.js


The build function will bundle all the *.js file inside js folder (page1.js and page2.js in this case). Other files in the sub-folders will not be built unless they are required by page1.js or page2.js. For example

• page1.js
• page2.js

# NPM packages

Here are all the npm packages needed for running this gulpfile

# Browserify Config

In order to use the short path page1/display.js instead of the ./page1/display.js, we need to specify the Browserify path config in gulpfile.js like this

# Bundle function

Usually, the gulpfile will contain 3 tasks for building js files (build-dev, watch, build-prod), so we need a bundle function to avoid repetitive tasks

source is the Gulp blob, mode is one of the three [dev, watch, prod], bundler will be explained in the next section.

# Create Bundler function

Now the most interesting thing is the buildBrowserify I mentioned in the beginning. I will name it createBundler here. Please read the comment in the code for explanation

# Error handler

In the above code, if there are any error occur in the build process, the function browserifyError will be triggered with an error object. Here is how to define that function