Gulp for watching for changes to .less files and compiling to .css
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

Summary:

Write a gulpfile.js script to watch for changes to .less files in a given directory, and upon triggering a change, will re-compile the changed .less file to .css.

Input:

.less files live in ./public/less/

There will be .less files in the base of this directory, ex. ./public/less/styles.less

There may also be less files nested in subdirectories, ex. ./public/less/widgets/popups.less

Gulp should watch for changes to above director[y|ies] using gulp-watch and re-compile only the file that has changed using gulp-less

Output:

Compiled .css files should end up in ./public/css/

If the .less file was in a subdirectory, it should retain that subdirectory.

Ex: ./public/less/widgets/popups.css should end up in ./public/css/widgets/popups.css

Feedback:

Output of the process should write a message to console using gulp-debug AND a Growl message using gulp-notify.

On error, the message should be the name of the file and the less compile error

On success, the message should be Succesfully compiled [filename]

Should the .css files be minified?
weslly over 2 years ago
nope, minified not required. Will test out your solution below later today!
Difranco over 2 years ago
awarded to weslly
Tags
css
less
npm
gulp

Crowdsource coding tasks.

1 Solution

Winning solution

Here's my solution:

(Run with gulp watch)

Required npm packages

gulp
gulp-changed
gulp-debug
gulp-less
gulp-notify
gulp-plumber

gulpfile.js

var gulp = require('gulp'),
  plumber = require('gulp-plumber'),
  less = require('gulp-less'),
  notify = require("gulp-notify"),
  changed = require('gulp-changed'),
  debug = require('gulp-debug');


gulp.task('less', function () {

  var onError = function(err) {
      notify.onError({
          title:    "Error compiling less file",
          subtitle: "<%= error.filename.replace(/^.*[\\\/]/, '') %>",
          message:  "Error: <%= error.message %>",
          sound:    "Beep"
        })(err);
      this.emit('end')
    };

  return gulp.src('public/less/**/*.less')
    .pipe(changed( 'public/css', {extension: '.css'}))
    .pipe(plumber({errorHandler: onError}))
    .pipe(less({
      paths: [ './public/less/' ]
    }))
    .pipe(debug({title: 'Succesfully compiled '}))
    .pipe(notify("Succesfully compiled <%= file.relative %>!"))
    .pipe(gulp.dest('./public/css'));
});


gulp.task('watch', function() {
  gulp.watch("public/less/**/*.less", ["less"]);
});

gulp.task('default', ['watch']);