Update: I made a new better solution for this. You can read it here Using Gulp with Browserify and Watchify - Updated
Using Watchify instead of gulp.watch
If you are using Browserify with Gulp, perhaps gulp.watch
is not the best
solution when you want to watch for file changes and rebuild them as changes
happen. gulp.watch
cannot recognize the dependencies of each Browserify bundle
so every time you save your file, Gulp have to re-compile all your Browserify
bundles.
watchify is a solution for this.
Watchify will only re-compile the bundle if its dependencies change.
Using Watchify is very similar to normal Browserify. Watchify object is very similar to a Browserify bundle so you can take the code from Browserify to Watchify with very little change in code.
To use Watchify, take the Browserify code (you can read more in this post Browserify - Bring Nodejs modules to browsers), wrap it inside a Watchify object, add an on update event handler for it and you are done.
Watchify with other Gulp watch tasks
You will not need to activate the watch function all the time. Sometimes, you just need to compile the file and see the result. In that case, we can modify the above code a bit to create to different gulp tasks.
The below example demonstrate how to create 2 browserify task and attach the watch task with normal gulp.watch task. It also takes use of livereload server for auto web page reloading when the compilation finishes.
Error Handling
Error handling in Watchify is similar to that in Browserify and there are another blog post that I have written to describe to steps how to handle it properly. You can read it here Error Handling while using gulp.watch.
Update: I made a new better solution for this. You can read it here Using Gulp with Browserify and Watchify - Updated