Gulp – Uglify

Gulp, Gulp – Uglify

For JavaScript files we also want to uglify them. Uglifying JavaScript involves changing variable and function names to reduce their size. So a variable named customer might be renamed to x. JavaScript engines don’t care about descriptive names, only developers. So how do we uglify JavaScript files with gulp?

I know what you are going to say: “Blah, blah, blah… there is a plugin.” and you are correct.

1
$ npm install gulp-uglify --save-dev

For more information on gulp-uglify check out https://www.npmjs.org/package/gulp-uglify.

While we are uglifying the file, we will also concat all our JavaScript files together and move them to build/javascripts.

gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
...
var uglify = require('gulp-uglify');
...

gulp.task('javascript', function () {
  console.log("Validate, Concat, Uglify, and Move all the javascript files");

  return gulp.src("contents/javascripts/**.js")
    .pipe(jsValidate())
    .on("error", notify.onError(function(error) {
      return error.message;
    }))
    .pipe(uglify())
    .pipe(concat('main.js'))
    .pipe(gulp.dest('build/javascripts'));
});

When you run our gulp javascript task now, we should see that our javascript files were uglified, concated, and moved to the build folder.

1
2
3
4
5
6
$ gulp javascript

Using gulpfile ~/YOUR_DIRECTORY/gulpFile.js
Starting 'javascript'...
Validate, Concat, Uglify, and Move all the javascript files
Finished 'javascript' after 55 ms

If you have an error here, be sure to check that your JavaScript is valid. Remember we were testing that last section.

The build script should create our /build/javascripts/main.js file.

/build/javascripts/main.js
1
function OMG(){var n=2;return n+10}