24 May 2016

Gulp: Automate Development Workflow

Gulp (http://gulpjs.com/)
A tool-kit to automate painful or time-consuming tasks in your development workflow.

You can use npm to automate build tasks but there are inconsistencies between Windows and Unix based systems that make this sometimes a pain. Some people think we don't need gulp e.g. Keith Cirkel and Cory House. They may have a point. I've been using Gulp for a while now and I still find I have debugging, stream and concurrency issues. If you do decide to use it I recomment splitting the file out as it fast becomes large and difficult to manage. Callum Macrae has a good approach in 'Approach Two'. He also makes some good points for using Gulp in 'Gulp is Useful'.
  • Pre-requisites: npm and Bower
  • Install:
    • npm install -g gulp
    • npm install gulp --save-dev
  • Configure: See below
  • Run: gulp

Gulpfile.js

Example file:
/// <binding BeforeBuild='clean, bower-files, min' Clean='clean' />
"use strict";

var gulp = require("gulp"),
    rimraf = require("rimraf"),
    concat = require("gulp-concat"),
    cssmin = require("gulp-cssmin"),
    uglify = require("gulp-uglify"),
    mainBowerFiles = require("main-bower-files");

var project = {
    webroot: "wwwroot"
};

var paths = {
    webroot: "./" + project.webroot + "/",
    bower: "./bower_components/",
    lib: "./" + project.webroot + "/lib/"
};

paths.js = paths.webroot + "js/**/*.js";
paths.minJs = paths.webroot + "js/**/*.min.js";
paths.css = paths.webroot + "css/**/*.css";
paths.minCss = paths.webroot + "css/**/*.min.css";
paths.minifiedJs = paths.webroot + "js/site.min.js";
paths.minifiedCss = paths.webroot + "css/site.min.css";

// Clean js
gulp.task("clean:jsMin", function (cb) {
    rimraf(paths.minifiedJs, cb);
});

// Clean lib
gulp.task("clean:lib", function (cb) {
    rimraf(paths.lib, cb);
});

gulp.task("clean:cssMin", function (cb) {
    rimraf(paths.minifiedCss, cb);
});

gulp.task("clean", ["clean:jsMin", "clean:lib", "clean:cssMin"]);

// Bower files
gulp.task("bower-files", ["clean:lib"], function() {
    return gulp.src(mainBowerFiles({ debugging: true }))
          .pipe(gulp.dest(paths.lib));
});

// Minify
gulp.task("min:js", function () {
    return gulp.src([paths.js, "!" + paths.minJs], { base: "." })
        .pipe(concat(paths.minifiedJs))
        .pipe(uglify())
        .pipe(gulp.dest("."));
});

gulp.task("min:css", function () {
    return gulp.src([paths.css, "!" + paths.minCss])
        .pipe(concat(paths.minifiedCss))
        .pipe(cssmin())
        .pipe(gulp.dest("."));
});

gulp.task("min", ["min:js", "min:css"]);

// Default
gulp.task("default", ["clean"], function () {
    gulp.start("bower-files", "min");
});

No comments:

Post a Comment