Uglify

Learning Gulp : part 11 of 22 published on Aug 10, 2015

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.

$ npm install gulp-uglify --save-dev

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

// gulpfile.js
...
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.

$ 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
function OMG(){var n=2;return n+10}
Next: Testing with Jasmine