Sunday, 21 June 2015

Compile LESS with Gulp and Task Runner

A simple GULP compiling and minifying LESS files to CSS using Visual Studio Task Runner Explorer.

This example watches a folder containing LESS files and compiles them to CSS on any changes or when the project is built or cleaned.

By doing this you can have a primary LESS file, and when this or any referenced by it through “@import” statements, compiling to a single CSS file.



In this example, the primary LESS file is called “main.less”, it will be compiled to “main.css” and “main.min.css”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/// <vs afterbuild="project-build" clean="project-clean" solutionopened="project-start">
var gulp = require('gulp');
var concat = require('gulp-concat');
 
var less = require('gulp-less');
var minifyCss = require('gulp-minify-css');
var rename = require("gulp-rename");
var watch = require('gulp-watch');
var del = require('delete');
 
var sass = require('gulp-ruby-sass')
var notify = require("gulp-notify")
var bower = require('gulp-bower');
 
 
 
var MainConfig = {
    watch: ['main/**/*.less'],          //folder to watch for changes
    src: ['main/main.less'],            //main LESS file to compile
    targetDir: '../target-folder/css'//folder to output compiled CSS
    targetName: 'main',                 //name of compiled CSS file
    targetMinName: 'main.min'           //name of minified CSS file
}
 
 
function BuildMain() {
    gulp.src(MainConfig.src)
        .pipe(less())
        .on('error', swallowError)
        .pipe(gulp.dest(MainConfig.targetDir))
        .pipe(minifyCss())
        .on('error', swallowError)
        .pipe(rename({ basename: MainConfig.targetMinName, extname: ".css" }))
        .pipe(gulp.dest(MainConfig.targetDir));
 
 
    //If theres an error generating the css, delete the existing css files
    function swallowError(error) {
        var _cssName = MainConfig.targetDir + "/" + MainConfig.targetName + ".css";
        var _cssMinName = MainConfig.targetDir + "/" + MainConfig.targetMinName + ".css";
 
        del.sync(_cssName, { force: true });
        del.sync(_cssMinName, { force: true });
 
        this.emit('end');
    }
}
 
//Tasks to be used by Task Runner
gulp.task('project-start', function () {
    watch(MainConfig.watch, function () {
        BuildMain();
    });
});
gulp.task('project-clean', function () {
    BuildMain();
});
gulp.task('project-build', function () {
    BuildMain();
});
 
</vs>

The script is saved as “gulpfile.js” in the root of the project

No comments:

Post a Comment