The Mijingo Blog

Latest news, updates, free tutorials, and more from Mijingo.

Watching Your Project Files for Changes with Grunt

by Ryan Irelan

This is a written excerpt from our JavaScript Task Runners video course.

Grunt is a great tool for processing Sass files, image files, JavaScript, and more. But it would be a bummer if you had to stop and run Grunt every time we made changes to our files, right?

You’re in luck. Grunt can watch your project files for changes. This means that you can be coding along on your big website project and Grunt will automatically process your Sass files every time you make a change and save this files.

Pretty neat, huh?

To do that we’re going to use a watch task in Grunt. It is really easy to set up so let’s walk through it together. I’m assuming you already have a Grunt file set up and working. If not, the JavaScript Task Runners course will walk through that step-by-step for you.

Installing Grunt Watch

First, we need to install the grunt-contrib-watch plugin in our local project. We’ll use the --save-dev option so this is saved as a dependency in our package.json file.


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

and then load it in our Gruntfile:


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

Create the Watch Task

Next, we create the watch task so Grunt knows what to do when we run grunt watch on the command line. We’re only going to use grunt watch for dev tasks because it doesn’t make sense to have it continously build for production.


    watch: {
      css: {
        files: ['src/css/*.scss'],
        tasks: ['sass:dev']
      },
      js: {
        files: ['src/js/*.js'],
        tasks: ['uglify:dev']
      }
    }

We define the CSS files that we want to watch and the tasks we want to run when one of the files is changed. We’l define our file path and files to be any files in src/css that ends in .scss.

And we’ll call our sass:dev task when a matching file changes. Grunt will then run that task and reprocess our files.

We’ll define our js files now the same way, watching for any files in src/js that have the extension .js. When a change is detected by watch our uglify:dev task will run and process the javascript file.

Alright, let’s give it a try! Run


    grunt watch 

and it’ll keep the process running in Terminal waiting for a change.

Now, let’s change a file. And you can see it reprocessed that file automatically.

Very cool! You’re on your way to automating your web development workflow with Grunt watch.

If you want to learn more about the JavaScript Task Runners Rung Gulp, our 90 minute course will get your up and running quickly.

Filed Under: Free Tutorials, JavaScript Task Runners