Archive

Archive for March, 2015

Live reload with gruntjs

March 17, 2015 Leave a comment

Create a folder with any name you want (eg. “grunt-reload”) and create a file named “package.json” with the following contents:

{
  "name": "grunt-reload",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-express": "~1.2.1",
    "grunt-open": "~0.2.3",
    "matchdep": "~0.3.0"
  }
}

Run npm to install dependencies:

npm install

Create a file gruntfile.js with the following contents. Pay attention to change the base folder of the server to match the folder where you are creating the files fot this tutorial.
Also note that I’m specifying Firefox as the browser.

module.exports = function(grunt) {
// Load Grunt tasks declared in the package.json file
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

// Configure Grunt
grunt.initConfig({

// Grunt express - our webserver
// https://github.com/blai/grunt-express
express: {
    all: {
        options: {
            bases: ['C:/Users/lestivalet/Downloads/grunt-reload'],
            port: 8080,
            hostname: "0.0.0.0",
            livereload: true
        }
    }
},

// grunt-watch will monitor the projects files
// https://github.com/gruntjs/grunt-contrib-watch
watch: {
    all: {
            files: '**/*.html',
            options: {
                livereload: true
        }
    }
},

// grunt-open will open your browser at the project's URL
// https://www.npmjs.org/package/grunt-open
open: {
    all: {
        path: 'http://localhost:8080/index.html',
        app: "firefox"
    }
}
});

// Creates the `server` task
grunt.registerTask('server', [
    'express',
    'open',
    'watch'
    ]);
};        

Create an html file (call it index.html) with the following boilerplate code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello Grunt!</title>
</head>
<body>
    Hello Grunt!
</body>
</html>        

Start the server with the following command:

grunt server

After running the command you’ll notice that Firefox will open automatically the index.html file.

Keep the browser window opened and make same changes in the index.html file. After saving it should automatically be reloaded by the browser.

Categories: Uncategorized Tags: ,