H

April 15, 2015

All the projects I've worked on in the past three years have involved some sort of task runner (mostly Grunt). But now I've switched over everything to use Gulp. The difference—code over configuration, which in my experience is easier to understand and allows the developer to make it work best for their application.

Take this gulpfile for example:

/**
 * Gulpfile for Sweet-Project.
 */
var gulp = require('gulp');

// Plugins.
var concat  = require('gulp-concat');
var uglify  = require('gulp-uglify');

gulp.task('application-js', function() {
	return gulp.src([
			'js/**/*.js'
		])
		.pipe(concat('sweet-project.min.js'))
		.pipe(uglify({
			mangle: true,
			preserveComments: false
		}))
		.pipe(gulp.dest('../public/js'));
});

gulp.task('watch', function() {
	gulp.watch(['js/**/*.js'], ['application-js']);
});

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

You'll notice that it's sole purpose is to concatentate and minify all our JavaScript files inside the js directory.

But what happens if one of our JavaScript files contains a syntax error (thus breaking the whole minified file)? Well Gulp and [hopefully] the plugins we're using will catch the error and dump it to stdout. This is fine if we have the output of our watch command currently in view—and if not?

Enter Gulp Plumber & Gulp Notify. Ta-da!

Plumber will prevent pipe breaking errors caused by [possibly] rogue plugins (the kind that kill a watch command, how annoying). Notify will send messages to our Mac Notification Center, Linux notifications, Windows (native toaster), and even Growl.

Let's implement these now:

/**
 * Gulpfile for Sweet-Project.
 */
var gulp = require('gulp');

// Plugins.
var concat  = require('gulp-concat');
var uglify  = require('gulp-uglify');
var notify  = require('gulp-notify');
var plumber = require('gulp-plumber');

gulp.task('application-js', function() {
	return gulp.src([
			'js/**/*.js'
		])
		.pipe(concat('sweet-project.min.js'))
		.pipe(plumber({
			errorHandler: notify.onError('Error: <%= error.message %>')
		}))
		.pipe(uglify({
			mangle: true,
			preserveComments: false
		}))
		.pipe(gulp.dest('../public/js'));
});

gulp.task('watch', function() {
	gulp.watch(['js/**/*.js'], ['application-js']);
});

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

Now we can ensure all errors are caught and will not break the stream, and even better those errors will appear as notifications instantaneously.

Not bad, huh?

Next up: Eloquent and ZF2

Proceed