Live Reload any Web App

25 Dec 2013


One of the reasons I enjoy working with Yeoman is that it has live-reload functionality out of the box, which is something very cool as it saves a lot of time and its nice to look at your UI refresh the moment you press the save key. This got me thinking what if there was a simple way to enable any web app for live-reload. I did a little research and found out that almost every framework be it rails, asp.net MVC, Django etc has its own tools and shebangs for live-reload. Today I am going to show you how you can have a unified way to enable live-reload in any web app. For this tutorial I will be using a rails application but this can be applied to any web development stack. I will be using Grunt to accomplish this feat.

Now the first thing you need to do in your rails app is to create the following package.json at your root directory:

 {
  "name": "super-awesome-rails-app",
  "version": "0.0.0",
  "dependencies": {},
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-watch": "*"
  },
  "engines": {
    "node": ">=0.8.0"
  }
}

The important part in the above file is the devDependencies which include grunt and grunt-contrib-watch. You can play around with the other values as you please.

After creating the file:

npm install

The next step is to create the following Gruntfile.js:

'use strict';
module.exports = function (grunt) {
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.initConfig({
    watch: {
      coffeefiles: {
        files: ['app/assets/javascripts/*.js'],
        options: {
          livereload: true,
        }
      },
      erbfiles: {
        files: ['app/views/{,*/}*.erb'],
        options: {
          livereload: true,
        }
      }
    }
  });
}

As you can see we are telling the grunt-contrib-watch to keep an eye on our javascript files and our views of the rails application. These could be anything for any other web application framework (.cshtml for Asp.net MVC, .py for Python etc.). The next step is to include the following in your application.html.erb layout(or any other view/page you wish to have live-reload on):

<script src="http://localhost:35729/livereload.js"></script>

Finally all you need to do now is to open a terminal window, navigate to your web app dir and execute:

grunt watch

That’s it now whenever we save any changes to our .erb or .js files, the browser will automatically refresh. Have fun :)

Vote on Hacker News
blog comments powered by Disqus