Make Grunt watch for LESSCSS changes

Watching for less file changes is important for a quick and solid workflow with the CSS precompiler. Let's have a look at how you can make Grunt, the JavaScript task runner watch for changes in your LESS files and compile them to CSS automatically.

We're going to write a Gruntfile.js that allows us to simply type grunt watch to watch for changes in the .less file and will compile it to a compressed css file.

TLDR;

Install node, bower and grunt, clone the grunt-less-watch repository and slam it into your project.

Dependencies

Make sure you have node and npm installed, after that run the following:

npm install -g bower grunt

We will use bower to install bootstrap later, so we don't have to go to a website, download and unzip a file. Workflow baby!

The Grunt Watch Less Gruntfile

My project has a css/ directory where both my less and my css files will be.

Gruntfile.js
bower.json
bower_components
css 

The Gruntfile.js I found on stackoverflow and tweaked it for my purposes. Thanks to Thomas Reggi at this point! Here's the contents of my Gruntfile.js:

	module.exports = function(grunt) {
	grunt.initConfig({
		// running `grunt less` will compile once
		less: {
			development: {
				options: {
					paths: ["./css"],
					yuicompress: true
				},
			files: {
				"./css/style.css": "./css/style.less"
			}
		}
	},
	// running `grunt watch` will watch for changes
	watch: {
		files: "./css/*.less",
		tasks: ["less"]
	}
});
	grunt.loadNpmTasks('grunt-contrib-less');
	grunt.loadNpmTasks('grunt-contrib-watch');
};

In order for this to work, we need to run the following inside our project directory:

npm install grunt grunt-contrib-less grunt-contrib-watch
grunt watch

Now Grunt will watch our css directory and compile the file that we specified in the less task.

Using Boostrap Less with Grunt

Running bower install bootstrap we can open our style.less and include bootstrap while having Grunt running like so: @import './../bower_components/bootstrap/less/bootstrap.less';

Wrapping up

Now you've learned how to make Grunt watch less files. Even though this is not the primary concern of Grunt or where its biggest potential is, we all need to compile our less files and with this you can even automate the compilation, for example before a git push. This is my first time really using Grunt and I like it already!

Tagged with: #CSS #grunt #gruntjs #LESS

Thank you for reading! If you have any comments, additions or questions, please tweet or toot them at me!