Pages

Thursday, September 29, 2016

Inmadusa.com [Part 7]: Live reload the browser when you make changes with browser-sync

Up to now I have been using the local-web-server as the development server. It is time to switch to browser-sync so that developers don't have to install a global package as well as supporting live reload. Here is the gulp task that starts the server:
var bs = require('browser-sync').create();

gulp.task('browser-sync', function() {
    return bs.init({
        server: {
            baseDir: './'
        }
    });
});

Even though browser-sync has watch capabilities, I like to hook it up with gulp's watch task for greater control:
gulp.task('watch', function() {
    gulp.watch('templates/*.hbs', ['templates']).on('change', bs.reload);
    gulp.watch('css/*.css', ['css']).on('change', bs.reload);
});

Running the browser-sync task produces an output like this:
[BS] Reloading Browsers...
[BS] Access URLs:
 --------------------------------------
       Local: http://localhost:3000
    External: http://192.168.1.105:3000
 --------------------------------------
          UI: http://localhost:3001
 UI External: http://192.168.1.105:3001
 --------------------------------------
[BS] Serving files from: ./

It will also automatically launch your default browser and navigate to the site. The watch task will also make sure that as you make changes to any of the templates or css files the browser automatically refreshes.

This works fine for now and we are almost at the end of this series. In the next post I will go over how to set up cache invalidation of the script files when they change. Until then you can visit the live site or check the source code.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.