Preparation for using less in your grunt file
Install the less grunt plugin
npm install grunt-contrib-less –save-dev
In your Grunfile.js you can add less as a step in your run process. You can also set Grunt up to watch changes to your less files and then convert any less to css.
Step 1. Convert less to css using a Grunt task.
Adding the less task:
less: {
style: {
options: {
compress: false
},
files: {
‘app/css/style.css’ : ‘app/less/style.less’
}
}
}
The filepaths will need to be updated to where your css files and your less files are kept.
Step 2. Watch for changes to less files, then run the less Grunt task.
In your watch add the less task below:
Don’t replace the whole watch block, just add the less: section.
watch: {
… existing code …less: {
files: [‘app/less/*’],
options: {
livereload: ‘<%= connect.options.livereload %>’
},
tasks: [‘less’]
},… existing code …
}
The filepaths will need to be updated to where your less files are kept.
What the above does:
files: [‘app/less/*’]
This tells Grunt that it must watch all files in app/less/…
livereload: ‘<%= connect.options.livereload %>’
This tells grunt that when a change is done, the browser should reload (after the task is run).
Also with <%= connect.options.livereload %> the naming needs to be correct. This needs to link up with your “connect” task in the Gruntfile. There should be connect code at the bottom that looks something like this:
connect: {
…
options: {
port: 9220,
hostname: ‘localhost’,
livereload: 35700
},
…
}
tasks: [‘less’]
This tells grunt that when the change is spotted by the watch, these tasks need to run. In this case we just one one task to run, the ‘less’ task that we added to the Grunfile.js.
Extra step: styles watch
Another watch that is important to add, is the styles watch. When less updates your css, a second watch needs to then update the css files you use. This is for example built into a yeoman generated app with the following code:
watch: {
…
styles: {
files: [‘<%= yeoman.app %>/styles/{,*/}*.css’],
tasks: [‘newer:copy:styles’, ‘autoprefixer’]
},
…
}
Step 3. Add less task to your build/serve task
When you run “grunt serve”, you want less to run as well, before your css gets copied over. Add the less task to your serve task list:
grunt.task.run([
… existing code…
‘less’,
… existing code …
]);
Full example of the serve task with the new ‘less’ task added:
grunt.registerTask(‘serve’, ‘Compile then start a connect web server’, function (target) {
if (target === ‘dist’) {
return grunt.task.run([‘build’, ‘connect:dist:keepalive’]);
}
grunt.task.run([
‘clean:server’,
‘less’,
‘wiredep’,
‘concurrent:server’,
‘postcss:server’,
‘connect:livereload’,
‘watch’
]);
});