Live Development in Browser with Cordova and Grunt

16 Aug

When developing with Cordova you can use the serve functionality to launch a web server for viewing your application in a browser.  The problem here is that you’ll be browsing to the site in one of your platform directories where changes are not reflected until you run Cordova Prepare.  Through the magic of Grunt and grunt-contrib-watch, I’ve created a task that will monitor the \www directory for changes and call prepare automatically, while maintaining your Serve session concurrently.

So instead of doing this after each edit:

cordova prepare
cordova serve

 

You can just do this once:

grunt livedev

 

The task runs prepare first, then starts Cordova Serve.  In a seperate thread it monitors the www directory for changes and calls Cordova Prepare in the background as they are detected.  Update the watch task to exclude directories as needed, in this example I have excluded the WebStorm project directory.

 

As a prerequisite you’ll need to install grunt of course, and drop the gruntfile in your Cordova project next to packages.json.

 

The gruntfile:

module.exports = function(grunt){

 grunt.initConfig({
 pkg: grunt.file.readJSON('package.json'),
 exec:{
 prepare:{
 command:"cordova prepare",
 stdout:true,
 stderror:true
 },
 serve:{
 command:"cordova serve",
 stdout:true,
 stderror:true
 }
 },
 watch:{
 files:['www/**/*.*', '!www/.idea/**/*.*'],
 tasks:['exec:prepare']
 },
 concurrent: {
 Prepare: ['exec:prepare'],
 WatchAndServe: {
 tasks: ['exec:serve', 'watch'],
 options: { logConcurrentOutput: true }
 }
 }
 });

 grunt.loadNpmTasks('grunt-concurrent');
 grunt.loadNpmTasks('grunt-contrib-watch');
 grunt.loadNpmTasks('grunt-exec');

 grunt.registerTask('livedev', ['concurrent:Prepare', 'concurrent:WatchAndServe']);

};
Tweet about this on TwitterShare on Google+Share on FacebookShare on RedditEmail this to someoneShare on LinkedInShare on StumbleUpon

Leave a Reply

Your email address will not be published. Required fields are marked *