Share:     


Having learned a little Node.js in the last year, I recently tried my hand at the Gulp build tool. If you know some JS and want a flexible build tool, this is a great option for both front end and back end projects (or, in my case, both at the same time).

It’s quite simple for starters:

var gulp = require('gulp');

gulp.task('default', function() {
  // place code for your default task here
});

I’m building a site that has Node.js on the back end and Bootstrap on the front end. For this project, I needed Gulp to automate some of my front end code building process. I also needed to make my own theme customizations in LESS. Using several plugins, I was able to make Gulp take my finished CSS, limit it to only what is actually being used, add vendor prefixes where applicable, and minify it. As an added bonus, the needed build processes are triggered by a filesystem watcher when I turn it on (using “gulp watch” in my case). It took a bit of code, but once I got the hang of it then it felt fairly simple:

var gulp         = require('gulp');
var concat       = require('gulp-concat');
var less         = require('gulp-less');
var minify       = require('gulp-minify-css');
var postcss      = require('gulp-postcss');
var purify       = require('gulp-purifycss');
var rename       = require('gulp-rename');
var watch        = require('gulp-watch');
var autoprefixer = require('autoprefixer-core');

var css_dest = './public/css/';
var js_dest  = './public/js/';

gulp.task('jquery', function() {
  return gulp.src('./node_modules/jquery/dist/jquery.min.js').
    pipe(gulp.dest(js_dest));
});

gulp.task('bootstrap_js', function() {
  return gulp.src('./node_modules/bootstrap/dist/js/bootstrap.min.js').
    pipe(gulp.dest(js_dest));
});

gulp.task('bootstrap_css', function() {
  return gulp.src('./node_modules/bootstrap/dist/css/bootstrap.min.css').
    pipe(purify(['./index.html'])).
    pipe(gulp.dest(css_dest));
});

gulp.task('theme_css', function() {
  return gulp.src('./src/theme.less').
    pipe(less().on('error', function(err) {
      console.log(err);
      this.emit('end');
    })).
    pipe(purify(['./index.html'])).
    pipe(postcss([ autoprefixer({ browsers: ['last 3 versions'] }) ])).
    pipe(minify({ keepsBreaks: true })).
    pipe(rename({ suffix : '.min' })).
    pipe(gulp.dest(css_dest));
});

gulp.task('watch', function() {
  gulp.watch('./index.html', ['bootstrap_css', 'theme_css']);
  gulp.watch('./src/theme.less', ['theme_css']);
});

gulp.task('default', ['jquery', 'bootstrap_js', 'bootstrap_css', 'theme_css']);

In conclusion: if you are willing to write your JS build script in JS and want the flexibility of the streaming interfaces you will find the Gulp is a great solution with an active ecosystem.