Last Updated: February 25, 2016
·
1.459K
· dakuan

Getting bored of pressing F5 every time you change a file?

One of the most helpful things that you can do with the Grunt task runner is get it to kick off tasks when ever you change a file. Obvious uses for this would be compiling LESS, SASS of Coffeescript files or running unit tests.

Another would be to get the browser to reload the changed files so that after you make your CSS / Js / whatever edit, you tab back to the browser and the changes are right there - no need to press F5.

Fortunately, there is a plugin for that: contrib-livereload

The documentation clearly states to use the regarde plugin, rather than contrib-watch to inform the livereload plugin of changes to files.

Note that grunt-contrib-livereload is designed to use grunt-regarde instead grunt-contrib-watch (mainly due to shortcomings in the watch task which doesn't give access to changed files because it spawns tasks in subprocesses.)

So far so good, but the regarde documentation says:

[deprecated in favor of grunt-contrib-watch, click link below] Observe files for changes and run tasks — Read more
https://github.com/gruntjs/grunt-contrib-watch

Sad Face.

The good news is that the contrib-livereload documentation is out of date, and it will now play nicely with contrib-watch.

It requires slightly different configuration though...

First, you will need some bumf to insert into your middleware, put this at the top of your Gruntfile:

'use strict';
var path = require('path');

var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;

var folderMount = function folderMount(connect, point) {
    return connect.static(path.resolve(point));
};

Then, you will want to inject the livereloader into your middleware. I'm using connect and do this:

connect: {
    run: {
        options: {
            port: 9000,
            hostname: 'localhost',
            base: 'build/',
            middleware: function(connect, options) {
                return [lrSnippet, folderMount(connect, options.base)]
            }
        }
    }
},

Next, it's time to tell watch what to do:

watch: {
    sass: {
        files: ['source/**/*'],
        tasks: ['sass:dist', 'copy:build'],
        options:{
            livereload: true                    
        }
    }
},

And finally, the configuration for live reload itself:

livereload: {
       port: 35729 
   },