9/28/2014

[gulp] Minify Javascript Files and Add License Notice at Head

Suppose we have source file named "myApp.js" like
var myApp = (function(){
   var x = 1;
})();
We'd like to add license notice and build time at the head of minified file (i.e., "myApp-1.0.min.js") like
/**
 * License Notice
 * Version: 1.0
 * Build: Sun, 28 Sep 2014 02:41:31 GMT
 */
 var myApp=(function(){var x=1;})();
In this situation, we can use gulp to automate the process of minifying Javascript files.
1) Create 'LICENSE' file in project. Note that version and build time are variables which will be replaced when we run gulp task.
/**
 * License Notice
 * Version: <%= version %> 
 * Build: <%= build %>
 */
2) Create 'VERSION' file in the project like
1.0
3) Create gulpfile.js in the project.
var gulp = require('gulp'),
    uglify = require("gulp-uglify"),
    rename = require("gulp-rename"),
    fs = require('fs'),
    header = require("gulp-header");

var getLicense = function() {
    return '' + fs.readFileSync('LICENSE');
};
var getVersion = function() {
    return fs.readFileSync('VERSION');
};

gulp.task('minify-js', function() {
    var version = getVersion(),
        proudctionName = 'myApp-' + version + '.min.js',
        dest = './dist',
        src = './myApp.js';

    gulp.src(src)
        .pipe(rename(proudctionName))
        .pipe(uglify())
        .pipe(header(getLicense(), {
            version: version,
            build: (new Date()).toUTCString()
        }))
        .pipe(gulp.dest(dest));
});

4) After running the gulp task, the minified file will be at ./dist/myApp-1.0.min.js
gulp minify-js
In case you haven't installed gulp, here is quick tips to setup.
1) Install nodeJS
2) Install gulp, the streaming build system.
$ npm install -g gulp
$ npm install —-save-dev gulp
3) Install gulp-uglify, gulp-rename, and gulp-header
$ npm install --save-dev gulp-uglify
$ npm install --save-dev gulp-rename
$ npm install --save-dev gulp-header
This tutorial is based on this github project https://github.com/cwtuan/Locale.js. You can fork it to test if your setup work.