In my previous
2014-08-06-using-watchify-with-gulp-for-fast-browserify-build.md,
I have demonstrated how to use Browserify and Watchify in
Gulp to automate the build process. The steps are to
create a browserify bundle and return that bundle with a bunch of pipe inside a
gulp task like this
We have to manually add the main.js file into Browserify so it will become
ugly and complex when you have multiple bundles to build, not just one
main.js file. It would be much better if we can do something like this,
passing the source files as a glob as we usually do with Gulp
In this post, I will illustrate how to create that buildBrowserify function.
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