Automatically run Grunt tasks when files change

Hackered
Monday, August 25, 2014
by Sean McAlinden

Following on from my post Using Grunt to minify JavaScript, this post just shows a nice way to run tasks such as uglify when a file changes.

We are going to use the grunt-contrib-watch plugin.

Install Watch

Navigate to the root of your application and type the following:

npm install grunt-contrib-watch --save-dev

 

This will add the following to the packages.json devDependencies section:

"watch": "~0.11.0",
"grunt-contrib-watch": "~0.6.1"

 

Init Config

Add the following to the Gruntfile.js initConfig:

watch: {
    scripts: {
        files: ['Scripts/myTestJsFile.js'],
        tasks: ['uglify']
    }
}

We also need to install the plugin and add it to the tasks.

You code should now look like the following:

module.exports = function(grunt) {
 
    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        uglify: {
            options: {
                banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
            },
            build: {
                src: 'Scripts/myTestJsFile.js',
                dest: 'Scripts/myTestJsFile.min.js'
            }
        },
        watch: {
            scripts: {
                files: ['Scripts/myTestJsFile.js'],
                tasks: ['uglify']
            }
        }
    });
 
    // Load the watch plugin
    grunt.loadNpmTasks('grunt-contrib-watch');
 
    // Load the plugin that provides the "uglify" task.
    grunt.loadNpmTasks('grunt-contrib-uglify');
 
    // Default task(s).
    grunt.registerTask('default', ['uglify', 'watch']);
};

Now at the command line run the following to make sure everything is installed correctly:

npm install

Then run the following:

grunt

You should see a message stating:

Running "watch" task

Waiting...

Make a change to the javascript file and you will see the command line run the uglify task then continue waiting.

 

There you have it, a really cool file system watcher for grunt... nice.