Grunt & LESS – additional Grunt watch locations
Very quickly – I’m learning how to automate generating of LESS files without the need of manually running lessc from command line (Ubuntu).
A quick search reveals that you can use Grunt to automate this process.
Once Grunt was up and running, I was wondering how do I create additional Grunt watch locations?
For example my LESS files exist in the less/ directory for my project (by default).
I wanted to accomplish a structure like the following instead and have Grunt watch for changes in the project root as well:
However when I created this new structure, Grunt was not watching for changes made to project root\gurdeep2.less.
After a quick investigation of the Gruntfile.js
for my project, it reveals that by default Grunt is only watching for changes made in the less/**/ location (Line 3 of the snippet below):
watch: { styles: { files: ['less/**/*.less'], // which files to watch tasks: ['less'], options: { nospawn: true } } }
For additional Grunt watch locations, you have to tell the watch process to look at those additional locations.
After doing some quick reading of the Grunt Globbing Pattern, I was able to do this quite easily.
Gruntfile.js changes
Firstly open your project’s Gruntfile.js
. You’ll probably see something similar to this:
module.exports = function(grunt) { require('jit-grunt')(grunt); grunt.initConfig({ less: { development: { options: { compress: true, yuicompress: true, optimization: 2 }, files: { "css/gurdeep.css": "less/gurdeep.less" // destination file and source file } } }, watch: { styles: { files: ['less/**/*.less'], // which files to watch tasks: ['less'], options: { nospawn: true } } } }); grunt.registerTask('default', ['less', 'watch']); };
Pay attention to the changes for line 14 and line 20 below:
module.exports = function(grunt) { require('jit-grunt')(grunt); grunt.initConfig({ less: { development: { options: { compress: true, yuicompress: true, optimization: 2 }, files: { "css/gurdeep.css": "less/gurdeep.less", // destination file and source file "css/gurdeep2.css": "gurdeep2.less" // I've placed a less file in the project root } } }, watch: { styles: { files: ['less/**/*.less','*.less'], // which files to watch tasks: ['less'], options: { nospawn: true } } } }); grunt.registerTask('default', ['less', 'watch']); };
What the changes mean
Line 14
"css/gurdeep2.css": "gurdeep2.less" // I've placed a less file in the project root
First I declare the additional less file gurdeep2.less.
Line 20
files: ['less/**/*.less','*.less'], // which files to watch
Secondly I have then added an additional file location to watch for. This is accomplished by adding an additional item to the the files array: '*.less'
When the change is made, restart the grunt watch process and tweak your newly located less files – Grunt will begin to do it’s magic.