UglifyJS: concat and minify or viceversa?

fedeisas picture fedeisas · Jun 11, 2012 · Viewed 10.6k times · Source

I'm writing an app that uses many JS files. Underscore, Backbone, jQuery, jQuery plugins for sliders, several files for models, routers, collections and views.

In my dev machine, I load every file separately, but in production I use only one JS file (minified, gziped, less http req, etc.).

In my build process, each file in minified with UglifyJS and then concat into prod.js. Is this the correct way to build that file? Or should I concat each file into prod.js and then minify with UglifyJS?

Thanks a lot!

Answer

Tyler Eich picture Tyler Eich · Apr 24, 2014

I tested the output of each method using Gulp.

Test Setup

I used 9 JavaScript files totaling 19.15 kB when concatenated (not minified). Each file starts with a 'use strict'; statement.

Results:

  • Concatenate => Uglify: 7.993 kB
  • Uglify => Concatenate: 8.093 kB
  • Difference: 0.1 kB

Notes:

  • Concatenate => Uglify strips 8 of the 9 'use strict'; statements
  • Uglify => Concatenate preserves all 'use strict'; statements
  • A single 'use strict'; statement is 13 bytes. 8 × 13 bytes = 104 bytes, which accounts for the 0.1 kB difference.

Final Thoughts:

Use whichever order you prefer.

The difference between these two processes is negligible. Concatenate => Uglify could (theoretically) produce (barely noticeably) smaller files if both of the following are true:

  • Several of the individual files start with a 'use strict'; statement
  • There are many individual files

Here's the gulpfile.js I used:

var gulp = require('gulp'),
  concat = require('gulp-concat'),
  uglify = require('gulp-uglify');

var files = [
  '!app/scripts/**/*Spec.js', // Exclude test files
  'app/scripts/**/*.js'
];

// Register tasks
gulp.task('concat-min', function() {
  return gulp.src(files)
    .pipe(concat('script.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('dist'));
});

gulp.task('min-concat', function() {
  return gulp.src(files)
    .pipe(uglify())
    .pipe(concat('script.min.js'))
    .pipe(gulp.dest('dist'));
});