Lesson Weekend

We can optimize our JavaScript a little bit more by adding a minification task to our gulpfile. Minifying JavaScript means removing all unnecessary characters while preserving its functionality.

Humans need things like descriptive variable names, whitespace and new lines in order to easily read and debug our code. But your browser doesn't care about that. For example, we have a variable called email but as far as the browser is concerned it could be named e, as long as it is changed everywhere consistently.

Minifying with gulp-uglify

We can add minification to the end of our JavaScript chain of tasks so that after we have concatenated our files and browserified the result, we can then minify it. We'll need another package from npm:

$ npm install gulp-uglify --save-dev

Then we can use it by adding a require statement to our gulpfile.js:

gulpfile.js
var uglify = require('gulp-uglify');

Let's create a task to minify our app.js file after it has been browserified. For clarity, let's put this task after jsBrowserify, since the jsBrowserify task will be a dependency of our minification task.

gulp.task("minifyScripts", ["jsBrowserify"], function(){
  return gulp.src("./build/js/app.js")
    .pipe(uglify())
    .pipe(gulp.dest("./build/js"));
});

Now, we can run $ gulp minifyScripts, and it will run jsBrowserify, which will run concatInterface. We can see in the terminal printout that it works!

If we compare the minified app.js file to the old app.js file created by jsBrowserify, we'll see that they are very different. The minified version is literally one line. Really annoying for humans to read, but much faster for your browser. Now our JavaScript build tasks go in the order concatInterface -> jsBrowserify -> minifyScripts.

Terminology


  • Minification: The process of removing all unnecessary characters in JS files to optimize JavaScript execution.

Examples


The command to install the gulp-uglify package in a project:

$ npm install gulp-uglify --save-dev

The following is an example gulp task to minify scripts:

gulp.task("minifyScripts", ["jsBrowserify"], function(){
  return gulp.src("./build/js/app.js")
    .pipe(uglify())
    .pipe(gulp.dest("./build/js"));
});