Cordova livereload with grunt watch inside an emulator
Hello all,
Today we are trying to achieve effortless livereload while emulating a mobile device.
Requirements
- NodeJS
- Cordova
- Cordova-cli with platform added and working (android with android-sdk and/or ios with xCode)
- Grunt
Setup
- Navigate to your cordova root project folder and create a Gruntfile.js file with this content:
module.exports = function(grunt){ grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), exec:{ prepare:{ command:"cordova prepare", stdout:true, stderror:true } }, watch:{ files:['www/**/*.*'], tasks:['exec:prepare'], options : { livereload : 9090, } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-exec'); grunt.registerTask('default', ['watch']); };
- Create a package.json file in the cordova project root folder with this content:
{ "name": "my-cordova-folder", "version": "1.0.0", "description": "", "main": "Gruntfile.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": { "grunt": "^0.4.5", "grunt-contrib-watch": "^0.6.1", "grunt-exec": "^0.4.6" } }
- Run:
npm install
- Edit in your config.xml the config src parameter with the cordova server address:
<content src="http://127.0.0.1:8001" />
- Add to your index.html the following script in the head:
<script src="http://127.0.0.1:9090/livereload.js"></script>
Run
- Start a cordova serve service:
$ cordova serve
- Run in your command line in the root folder of your cordova project:
$ grunt
- Finally run cordova emulator
$ cordova run
And voilà! it’s done!
open the “your-device-name” folder and edit a file. The page should be refreshed because the grunt scripts watch the changes on www/ folder, propagate them in /platforms/xxx/ with cordova prepare and inform livereload.js that you made changes (on www, but it’s the same since you run cordova prepare and you are looking at /platforms/xxx/ version) causing the page to refresh.
Thanks gave me some ideas for my own implementation, didnt know content can be served by a webserver in cordova