livereload is a little project that dramatically changes a front end developer’s life. it watches the filesystem for changes and will tell the browser to reload the page if it detects changes on the filesystem.
the idea by itself is pretty awesome. the actual implementation of this is a little weird as there appears to be a standalone app and a browser plugin that communicates with each other to detect the file changes and then trigger a browser reload.
but wait, there’s something even cooler! the livereload node module is an implementation of the livereload server in node.js. you can hook this into your node application and then you won’t need a separate app to monitor for file changes in your codebase. but still, there is some friction here because you still need that browser plugin so that the livereload server can trigger a browser reload.
but if you look at what the plugin does, all it does is inject some javascript on the page to call the livereload server, load up a javascript file, and initiate the websocket connection to listen for triggers. it turns out that you can simply add that script call to your page and then you won’t need the browser plugin at all.
it is technically documented but buried pretty deep in the knowledge base.
livereload is a separate server running in your app, so you just need to stick the code somewhere after your main server has been initiated, i put it at the buttom of my server.js file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var livereload = require('livereload'); var server = livereload.createServer({ exts: [ 'dust' ] }); server.watch(__dirname + '/config'); server.watch(__dirname + '/controllers'); server.watch(__dirname + '/lib'); server.watch(__dirname + '/locales'); server.watch(__dirname + '/models'); server.watch(__dirname + '/public'); |
livereload accepts a parameter “exts” which tells it which file extensions to watch. you can add as many server.watch() paths as you want for directories to watch.
then you just need to add this snippet to the bottom of your page template to have the browser connect the livereload server with your app:
1 2 3 |
<script> document.write('<script src="http://' + (location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1"></' + 'script>'); </script> |
and voila, if you make an update to a file in your project, your browser will automatically reload for you.