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.
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
Gulp tasks
Now we have everything we need to build Browserify bundles, the final thing to
do is to create some Gulp tasks for calling them
Sample gulpfile
I made a sample gulpfile for this example
here,
feel free to take if you like