Gulp: Live-reloading with Browser Sync

16 Apr 2017
0
comments

Browser Sync helps make web development easier by spinning up a web server that helps us do live-reloading easily. It has other features, like synchronizing actions across multiple devices, as well.

We'll first have to install Browser Sync:

$ npm install browser-sync --save-dev

You may have noticed that there isn't a gulp- prefix when we install Browser Sync. This is because Browser Sync works with Gulp, so we don't have to use a plugin.

To use Browser Sync, we'll have to require Browser Sync.

var browserSync = require('browser-sync').create();

We need to create a browserSync task to enable Gulp to spin up a server using Browser Sync. Since we're running a server, we need to let Browser Sync know where the root of the server should be. In our case, it's the `app` folder:

We're done with configuring Browser Sync. Now, we have to run both the watch and browserSync tasks at the same time for live-reloading to occur.

It'll be cumbersome to open up two command line windows and run gulp browserSync and gulp watch separately, so let's get Gulp to run them together by telling the watch task that browserSync must be completed before watch is allowed to run.

We can do so by adding a second argument to the watch task. The syntax is:

Now, if you run gulp watch in the command line, Gulp should start both the sass and browserSync tasks concurrently. When both tasks are completed, watch will run.

At the same time, a browser window that points to app/index.html would also pop up. If you change the styles.scss file, you'll see that the browser reloads automatically.

There's one more thing before we end this live-reloading section. Since we're already watching for .scss files to reload, why not go a step further and reload the browser if any HTML or JavaScript file gets saved?

We can do so by adding two more watch processes, and calling the browserSync.reload function when a file gets saved:

Spinning up a web server for development
Using the Sass preprocessor
Reloading the browser whenever a file is saved
Let's cover the part on optimizing assets in the next section. We'll start with optimizing CSS and JavaScript files.
Click here for For next Step:
"Optimizing CSS and JavaScript files"