how to minify multiple javascript files using yuicompressor node module

prerequisites

  1. install node js and npm
  2. install yuicompressor using the command npm install yuicompressor

A short tutorial on, how to use yuicompressor is available on https://www.npmjs.com/package/yuicompressor

Here is a small javascript program which helps you to compress multiple files.

var compressor = require('yuicompressor');

var compressorOptions = {
    //Compressor Options:
    charset: 'utf8',
    type: 'js',
    nomunge: false
}

// This is the list of javascript files to be compressed, which is located in different paths
var file = [{
	"path": "assets/www/js/app/controllers/",
	"type": "js",
	"name": ["controller1", "controller2", "controller3", "controller4", "controller5", "controller6", "controller7", "controller8", "controller9"]
},
{
	"path": "assets/www/js/login/controllers/",
	"type": "js",
	"name": ["controller1", "controller2", "controller3", "controller4", "controller5", "controller6", "controller7"]
},
{
	"path": "assets/www/lib/",
	"type": "js",
	"name": ["overlays"]
}];

function minify(i, j){
	i = (i == undefined) ? 0 : i;
	j = (j == undefined) ? 0 : j;
	filePath = file[i].path;
	fileType = file[i].type;
	name = file[i].name[j];
	fileName = filePath+name+"."+fileType;
	minifiedFileName = filePath+name+".min."+fileType;
	if(j == file[i].name.length - 1){
		i += 1;
		j = 0;
	}
	else
		j += 1;

	compressor.compress(fileName, compressorOptions, function(err, data, extra) {
		var fs = require('fs');
		fs.writeFile(minifiedFileName, data, function(err) {
			if(err) {
				console.log(err);
			} else {
				console.log("The file "+minifiedFileName+" was saved successfully!");
				if(i != file.length)
					minify(i, j);
				
			}
		}); 
	});	
		
		
}

minify(0,0);
  1.  Save  the above code as minify.js
  2. goto command prompt, goto the path where this file is saved and run the command node minify.js

Leave a Reply

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