The Simplest LiveReload with Grunt
Livereload is very cool feature. It automatically watch file changes and notify to browser to update the page. So, you don't need to refresh your page whenever update happens.
I can summarize it with two components;
Server-side watcher and notifier
This can be complete with
1) livereload server($10)
2) or, your own server watch and notify to browser using websocket
Client-side message consumer
This can be complete with
1) livereload browser extension(or plugin)
2) or, your own javascript to consume messages
As a programmer, I wanted to complete this feature with 2) and 2) both using my own script.
After two days of work, I was very close to rollout my version of livereload. However I figured out I can achieve this feature without any of my code, which means no maintenance.
The best programming is, no programing
To do so, you need to install the following node moduels
$ npm install grunt-contrib-watch grunt-contrib-connect connect-livereload --save-dev
grunt-contrib-watch is to monitor file changes and notify those to browsers using websocket with port 35729.
grunt-contrib-connect is to serve your files through http. You can also inject your own middleware
connect-livereload is the middleware used by grunt-contrib-connect to inject(add your your own script) to every single page.
The following is my gruntfile.js
module.exports = function (grunt) { // Load Grunt tasks declared in the package.json file require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.initConfig({ connect: { all : { options: { port: 9000, middleware: function(connect, options) { return [ require('connect-livereload')({ src: "//rawgithub.com/allenhwkim/util/master/livereload.js" }), connect.static('examples'), //http server base directory connect.directory('examples') //allow directory browsing ]; } } } }, watch: { all: { files: ['app/**/*', 'examples/*'], options: { livereload: true // starts livereload server at port 35729 } } } }); grunt.registerTask('server', ['connect', 'watch']); };
It uses my own livereload.js file using websocket client. I have tried with the existing livereload.js with no luck, and I don't need all the features provided from that anyway.
This is the code, you can find at https://github.com/allenhwkim/util/blob/master/livereload.js
/** * The following code will be injected every single page served by grunt-contrib-connect */ (function() { var ws = new WebSocket("ws://localhost:35729"); ws.onmessage = function(msg) { console.log('received message', msg); if ((JSON.parse(msg.data)).command == "reload") { window.location.reload(); } }; })();