
From LESS to CSS with Grunt.js
Dealing with CSS on big projects can be a mess. Now, with CSS Preprocessors it’s become much easier. These tools are really useful and completely change the way front-end developers work.
Take a look at LESS, you can play with variables, mixins, functions…
But how can I best use it? Which tool can I use to simply generate my CSS?
Grunt.js to manage your files
Grunt.js is a “task runner” which lets us - among a lot of other things - configure how our LESS files will be compiled. It’s really easy:
- You need Node.js to be installed
- Then, in your Terminal:
sudo npm install -g grunt-cli
sudo npm install grunt --save-dev
- Create and configure the gruntfile.js for LESS with the grunt-contrib-less task, as shown in the documentation:
module.exports = function(grunt) {
grunt.initConfig({
less: {
development: {
options: {
paths: ["assets/css"]
},
files: {"path/to/result.css": "path/to/source.less"}
},
production: {
options: {
paths: ["assets/css"],
cleancss: true
},
files: {"path/to/result.css": "path/to/source.less"}
}
}
});
grunt.loadNpmTasks('grunt-contrib-less');
grunt.registerTask('default', ['less']);
};
- Add and configure a package.json file:
{
"name": "my-project-name",
"version": "0.1.0",
"devDependencies": {
"grunt": "~0.4.2",
"grunt-contrib-less": "~0.8.2"
}
}
- Install the dependencies:
npm install
- And that’s it, just run grunt to see the result
grunt
Ok, this is the “simplest” version, if you dive into Grunt, you can easily watch the files to re-generate the css when you modify your LESS, setup a live reload, test the syntax of your files, use templates, …
Personally, I prefer SASS for some reasons, notice that it also works with Grunt.