Most questions and answers on this site do not contain an easy-to follow general approach to using these two libraries together.
So, being that we use the gulp-connect npm package, and we want to make use of the gulp-watch npm package, how do we set it up so that we can:
- watch changes in some files
- perform some operation, like building / compiling those files
- live-reload the server once the building is done
First, you will define your build task. This can have pre-required tasks, can be a task of some sort, it doesn't matter.
Then, you will need to activate the connect server. It is important that you are serving the result of the compilation (in this example, the
distdirectory) and you're enabling livereload with thelivereload: trueparameter.Finally, you will setup your watch logic. Note that we're using
watchand notgulp.watch. If you decide to change it, notice that their APIs are different and they have different capabilities. This example usesgulp-watch.The
watch-and-reloadtask will depend on thebuildtask, so that it ensures to run at least one build.Then, it will watch for your source files, and in the callback, it will start the
buildtask. This callback gets executed every time that a file is changed in the directory. You could pass an options object to thewatchmethod to be more specific. Check the usage API in their repository.Also, you will need to start the
buildaction, for which we're usinggulp.start. This is not the recommended approach, and will be deprecated eventually, but so far it works. Most questions with these issues in StackOverflow will look for an alternative workaround that changes the approach. (See related questions.)Notice that
gulp.startis called synchronously. This is what you want, since you want to allow thebuildtask to finish before you proceed with the event stream.And finally, you can use the event stream to reload the page. The event stream will correctly capture what files changed and will reload those.