Building upon the
watch task that we begin this lesson with, we’ll look at how to create a local development server using the
app directory as the web root. By using Browsersync to achieve this, we can also instruct all connected browsers to automatically reload each time our bundle is re-generated. Browsersync has a public
.stream() method that is designed exactly for this purpose.
Here we have Gulp and Browserify set up so that we can either run the js task to create a bundle once, or we can call the watch task and use Watchify to regenerate the bundle any time a file changes. That's pretty cool, but the next thing we need to do is add a local development server that we can inform to reload every single time the bundle changes. So for that we'll use Browsersync.
NPM install Browsersync, and then we'll bring it into our gulp file, call the create method to get a brand new instance and we'll start Browsersync in the watch task after Watchify is already up and running. So we'll call Browsersync.init, and if we pass the server option, this will create a local development server using one of our directories. So in our case, we have an index.html inside the app directory, so we can simply pass this string and Browsersync will do the rest.
When working with Gulp, it's useful to set the log file changes to false, you'll see why in a moment. That's enough to start the server, but we need to inform Browsersync every time our bundle is updated. To do that we can pipe after we've written the file to disk, into Browsersync.stream. This is a special function within Browsersync which basically is a through stream which doesn't act on any files, it just looks at the file names as they come through, and tries to decide what to do with them.
If we go back to our terminal window, we can see that the size of the bundle has been logged, along with how long it took to generate. Remember when I mentioned about log file changes, we set this to false because if it were true, every time our bundle was generated, Browsersync would log that this bundle file had changed, and we'd get a lot of console output here that we really don't need, so that's why we set that to false.