From LESS to CSS with Grunt.js

Pierre Fritsch
Pierre Fritsch, 17. März 2014

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:

  1. Install Grunt
    • You need Node.js to be installed
    • Then, in your Terminal:
      sudo npm install -g grunt-cli
       sudo npm install grunt --save-dev   
      
  2. 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']);
         };
    
  3. 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"
             }
         }
    
  4. Install the dependencies:
         npm install
    
  5. 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.