Search code examples
javascriptnode.jsgruntjsgrunt-contrib-watch

Grunt - Execute and Watch application at same time


I was developing a simple node application and I came across this tool called grunt-cli.

After intro to grunt I planned to use it with my application.

Gruntfile.js

module.exports = function(grunt){

    grunt.initConfig({
        execute: {
            target:{
                src: ['app.js']
            }
        },
        watch: {
            scrpits: {
                files: ['app.js'],
                tasks: ['execute'],
                options: {
                    spawn: false
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-execute');
    grunt.loadNpmTasks('grunt-contrib-watch');

    grunt.registerTask('default', ['execute', 'watch']);
};

package.json

{
  "name": "exampleapp",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Priyank Thakkar",
  "license": "ISC",
  "dependencies": {
    "express": "^4.14.0",
    "grunt": "^0.4.1"
  },
  "devDependencies": {
    "grunt-contrib-watch": "^1.0.0",
    "grunt-execute": "^0.2.2"
  }
}

app.js

var express = require('express');

var app = express();

app.set('port', process.env.port || 3005);

app.listen(3005, function(){
   console.log('application started at http://localhost:' + app.get('port'));
});

Is it correct to run execute followed by watch? Somehow I feel terminal is stuck at execute task only, it is not watching the changes in app.


Solution

  • Your grunt execute target is blocking watch and never ends. These two tasks need to run in separate threads.

    You could use something like grunt-concurrent to execute both these tasks simultaneously: https://github.com/sindresorhus/grunt-concurrent