How to Fix Slow Gulp Uglify  Builds

Reduce a JS build task with Uglify from 15-20 secs to 500ms.

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.

Meet the Author

Kevin Leary, WordPress Consultant

I'm a custom WordPress web developer and analytics consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.