Gulp Minify & Concat Javascript

To optimize the page speed we must do javascript minification and concat multiple javascript file to single file. Suppose we have a manifest.json file which has two nodes one for the libraries javascript files name array and second for all custom javascript file name array.
We have a const for build folder where all minified fill will save.

var gulp = require('gulp'),
    concat = require("gulp-concat"),
    eslint = require('gulp-eslint'),
    beautify = require('gulp-beautify'),
    uglify = require('gulp-uglify'),
    removeEmptyLines = require('gulp-remove-empty-lines'),
    fs = require('fs'),
    DIR = 'build/',
    ManFile = "manifest.json";

First we need all these packages for javascript minify and concat. Below is the task for creating two different version of js file one is debug and another is min file.

gulp.task("copy-js",function(){
	var manifestFile = './'+ManFile,
        json = JSON.parse(fs.readFileSync(manifestFile)),
        libs = json.libraries,
        scripts = json.scripts;
    
    gulp.src(libs)
	    .pipe(concat({
	        path: 'library.js',
	        stat: {
	            mode: '0666'
	        }
	    }))
	    .pipe(uglify())
	    .pipe(gulp.dest(DIR));

    gulp.src(scripts)
    	.pipe(concat({
	        path: 'static.js',
	        stat: {
	            mode: '0777'
	        }
	    }))
        .pipe(beautify({indentSize: 2}))
	    .pipe(eslint({
	      baseConfig: {
	        "ecmaFeatures": {
	           "jsx": true
	         }
	      }
	    }))
	    .pipe(eslint.format())
	    .pipe(eslint.failAfterError())
	    .pipe(minify({
	        ext:{
	            src:'.debug.js',
	            min:'.min.js'
	        }
	    }))
	    .pipe(strip())
	    .pipe(removeEmptyLines({removeComments: true}))
	    .pipe(gulp.dest(DIR));
});

This task will create on library.js file in build folder and static.debug.js & static.min.js for all custom files into one file. Next we need to inject these path to our html page. for injecting the css and js please check Inject Js & CSS Path

Leave a Reply

Your email address will not be published. Required fields are marked *