Compiling LESS to CSS using gulp

LESS in one the most widely used CSS Pre-processor. It makes writing and managing CSS a breeze.
Bootstrap (upto v3) also uses LESS. Here We will have a look at compiling LESS to CSS using gulp.

Requirements

  1. Install gulp globally.
  2. Include gulp, gulp-less in your devDepenedencies.
  3. Create a gulpfile.js file.

First, we need to install gulp globally by running the following command

npm install -g gulp

Next, we need to add gulp to devDependencies of one of your projects. Make sure you have a package.json file, either created manually or by typing npm init. Once you have a package.json file, run the following command:

npm install --save-dev gulp gulp-less

And finally, we need a gulpfile.js file, where we can define our tasks. Make sure you have this file in the root of your project and add the following code to it.

var gulp = require("gulp"),
    less = require("gulp-less");
 
gulp.task("default", function(){
    gulp.src("./src/**/*.less")
        .pipe(less())
        .pipe("./dist/css");
});

Now create a folder named src and add any less file in it. For sake of this example, let us add a test.less with following content.

@margin: 0;
 
html {
    margin: @margin;
}

Now run gulp command in your terminal and you must see something similar to this.

> gulp
[19:21:04] Using gulpfile ~/projects/gulp/gulpfile.js
[19:21:04] Starting 'default'...
[19:21:04] Finished 'default' after 20 ms

You'll see that dist/css/test.css is created, with following contents:

html {
  margin: 0;
}

You can add more files as per requirements and they will be converted and outputed to dist folder.

Leave a Reply