Search code examples
gruntjslivereloadgrunt-contrib-watchgrunt-contrib-connect

Setting up grunt to launch & live reload browser (with minimal plugins)


I'm setting up a web project and want to use grunt for automation and workflow. I have sass, jshint, jsdocs, minifiers all playing nice but am having no end of trouble with launch & reload of browser from the grunt shell.

I have 2 conditions I'd like to meet in doing this:

No browser plugins. (I want it to work straight out of the repo; "npm install", "grunt") Keep npm modules to a minimum. (Ideally just grunt-contrib-watch & grunt-contrib-connect)

This is my config for those 2:

connect: {
    options: {
        base: 'app/',
        port: '8888',
        livereload: true
    }
},

watch: {
    all: {
        files: [
            'gruntfile.js',
            'app/index.html',
            'app/partials/*.html',
            'app/styles/sass/*.scss',
            'app/scripts/*.js'
        ],
        tasks: ['default'],
        options: {
            livereload: true
        }
    }
}

In testing I have also tried:

connect: {
    options: {
        base: "app/",
        port: 8888,
        open: {
            target: 'app/index.html'
        }
    }
}

Watch tells me when files change, but running the default task (or any of the sub-tasks it's made from) does not launch a browser/page and there seems to be no reload.

I had some success with grunt-open, but I'm lead to believe it should be achievable with just grunt-contrib-watch after version 0.6.0 ?

----- additional I'm also unsure if grunt-contrib-connect is being run...

grunt.registerTask('serve',   ['sass', 'connect', 'watch']);
grunt.registerTask('default', ['jshint', 'serve']);

Results in the following, I don't see any timings for connect, I'm guessing the task is not measured because it runs in parallel, but is this what is happening?

Execution Time 
loading tasks  12ms  ▇▇▇▇▇ 10%
jshint:src     78ms  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 62%
sass:all       11ms  ▇▇▇▇▇ 9%
watch          24ms  ▇▇▇▇▇▇▇▇▇ 19%
Total 126ms

Solution

  • Well, not sure if this is it, but with your update I see that connect wouldn't ever run because you have no target specified:

    connect: {
        server: {  // try adding this block
            options: {
                base: 'app/',
                port: '8888',
                livereload: true
            }
        }
    },
    

    Otherwise, this looks mostly correct, but you could also explicitly state what port you want to live reload:

    watch: {
        all: {
            files: [
                // ...
            ],
            tasks: ['default'],
            options: {
                livereload: 8888  // changed...
            }
        }
    }