Gulp Uglify Faster BuildsI use gulp-uglify to minify my JavaScript for a large Angular.js project. Recently the compile process became incredibly slow, taking upwards of 15 seconds to compile JavaScript each. I’m convinced there is an underlying issue here, but for now I was able to solve the issue using a filesystem cache. This reduced a the JS build task with Uglify from 15-20 secs down to 500ms-1.5secs.

How to Fix It

Install gulp-fs-cache and add it to your gulpfile.js build routin

const fsCache = require( 'gulp-fs-cache' );

Next, update your pipe or call to uglify() with two additions, one before and one after:

.pipe( jsFsCache )
.pipe( uglify() )
.pipe( jsFsCache.restore )

A Look at My Setup

Note: I use pump() to group multiple calls to pipe() together.

Before

Here’s what my build looked BEFORE adding the filesystem cache.

const gulp = require( 'gulp' );
const include = require( 'gulp-codekit' );
const uglify = require( 'gulp-uglify' );
const sourcemaps = require( 'gulp-sourcemaps' );
const pump = require( 'pump' );
const ngAnnotate = require( 'gulp-ng-annotate' );

// Compile JavaScript
function compileJS() {
    return pump( [
        gulp.src( 'ng/main.js' ),
        sourcemaps.init(),
        include(),
        ngAnnotate(),
        uglify(),
        sourcemaps.write( 'maps' ),
        gulp.dest( './dist/js' )
    ], pumpDone );
}

After

Here’s what my build looked AFTER adding the filesystem cache.

const gulp = require( 'gulp' );
const include = require( 'gulp-codekit' );
const uglify = require( 'gulp-uglify' );
const fsCache = require( 'gulp-fs-cache' );
const sourcemaps = require( 'gulp-sourcemaps' );
const pump = require( 'pump' );
const ngAnnotate = require( 'gulp-ng-annotate' );

// Compile JavaScript
function compileJS() {
    var jsCache = fsCache( '.gulp-cache/js' );

    return pump( [
        gulp.src( 'ng/main.js' ),
        sourcemaps.init(),
        include(),
        jsCache,
        uglify(),
        jsCache.restore,
        sourcemaps.write( 'maps' ),
        gulp.dest( './dist/js' )
    ], pumpDone );
}

I’m pretty certain there is an underlying issue with the work that Uglify is doing. I commonly use the Codekit app for similar builds and I’ve found that using Uglify on the exact same project results in build <1 sec. I’ve tried matching the exact Uglify config that Codekit uses but haven’t had any luck. I’ll continue to investigate and hopefully uncover the root cause but for now this approach does improve workflow speeds.