Minimize Your Javascript Source Code By YUI Compressor

On September 25, 2014, in Other Online Technology, by James Liu
javascript

Web application or web app is a ideal solution to implement a cross platform applicatoins. In a web app, we may use lots of JavaScript files. Especially when we want to design a great app with well formed structure, we may create one JavaScript file for each one Class. Hence, there may be over dozens of files in one web app. As we know that all browsers have a limitation of http simultaneous connection from a given domain and a limitation of total concurrent connection (Browser profiling). The connection includes downloading images, CSS files, JavaScripts, etc. It will take very long before user can start to use the app. There are two ways to reduce the loading time. One is reducing the file size. Another one is reducing the number of files to be downloaded.

Combine Multiple JS File Into One File By Node.js

As a professional project, we will host one JavaScript class as one file. In this way, we can keep the source code more well structured and much easier to maintain. To reduce the loading time when we launch the web app, we’d bette to combine all JavaScript files into one file. In my latest JavaScript project, I am writing a Node.js script to go through the whole JS project folder, read all JS file and write into one file. Here is the Node.js source code:

var targetJS = "deploy.js";
var fs = require("fs");
readFolder("./", "js");
function readFolder(path, folderName) {
	var target = path + folderName;
	if (fs.existsSync(target)) {
		stats = fs.lstatSync(target);
		if (stats.isDirectory()) {
			var fileList = fs.readdirSync(target);
			for(var i=0; i<fileList.length; i++) { //fix ">" problem
				var file = target + "/" + fileList[i];
				var fileStats = fs.lstatSync(file);
				if(fileStats.isDirectory()) {
					readFolder(target + "/", fileList[i]);
				} else if(fileStats.isFile()
							&& getExtension(file) == ".js") {
					console.log(fileList[i]);
					var content = fs.readFileSync(file, "utf8");
					content += "\n";
					fs.appendFileSync(targetJS, content);
				}
			}
		}
	}
}

function getExtension(filename) {
    var i = filename.lastIndexOf('.');
    return (i < 0) ? '' : filename.substr(i); //fix ">" problem
}

The above Node.js script will go through the given folder and read all JS file into one final file. In this way, we can combine all JS files in our project into one file for deployment.

Minify Your Javascript Code By YUI Compressor

YUI Compressor is a great tool to help you minify and obfuscate your JavaScript source file. It is an open source project which is hosted on Github. For more information, you can check this page.

Here I want to mention the problem of obfuscate local symbols feature. In the YUI compressor document, it provides an example about how to use YUI compressor in Node.js. In that example, there is an option “nomunge”. The example show we can pass bool value “true” or “false” to enable or disable the obfuscate local symbols when we try to compress the JS files. After several testing, I find that the obfuscate function is always disabled no matter what value I pass. To enable the obfuscate function, I need to delete this option. Then, the YUI compressor works perfectly. Here is my Node.js script source code.

var deployTarget = "target.js";
var minTarget = "target-min.js";
var compressor = require('yuicompressor');
compressor.compress(deployTarget, {
    //Compressor Options:
    charset: 'utf8',
    type: 'js',
    'line-break': 80
}, function(err, data, extra) {
    //err   If compressor encounters an error, it's stderr will be here
    //data  The compressed string, you write it out where you want it
    //extra The stderr (warnings are printed here in case you want to echo them
	var fs = require('fs');
	fs.writeFileSync(minTarget, data);
	console.log("Done!");
});
 

Leave a Reply

Free WordPress Themes

Premium WordPress Themes