In Getting Started with UglifyJS, the installation and configuration of UglifyJS are mainly recorded. At the end of the article, a simple command is used on the command line to compress a JS file. This article uses programmatic method to compress JS files. That is, write a build.js file and use the node command to execute the file. The code in build.js will call the interface function of UglifyJS to perform the compression task.
1. Go to github to download the latest UglifyJS. There are two ways to download. If git is installed, enter the git console and use the following command
git clone git://github.com/mishoo/UglifyJS.git
or use http method to download, click zip download. After decompression, the directory structure is as follows
2. Create a new project (folder) myApp and copy uglify-js.js and lib directory to your own project. As follows
3, create a new compress.js in myApp with the following content
varfs = require('fs');
varjsp = require("./uglify-js").parser;
varpro = require( "./uglify-js").uglify;
varorigCode = "var abc = function(){ var one = 5; return one;}";
varast = jsp.parse(origCode); // parse code and get the initial AST
ast = pro.ast_mangle(ast); // get a new AST with mangled names
ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
varfinalCode = pro.gen_code(ast); // compressed code here
console.log(finalCode);
The general meaning of this code is to take the fs module, which is the file module of node. Then take the two modules of UglifyJS. What follows is the compression process of UglifyJS.
4. Open the command line and execute compress.js
The console outputs the compressed code. Well, it’s that simple.
5. Since it is in the node environment, of course you can write a function to directly read the source file, compress it and output it to the specified directory. Encapsulate the above code into a function, as follows
// Read a file and compress it
function buildOne(flieIn, fileOut) {
var origCode = fs.readFileSync(flieIn, 'utf8');
var ast = jsp. parse(origCode);
ast = pro.ast_mangle(ast);
ast = pro.ast_squeeze(ast);
var finalCode = pro.gen_code(ast);
(fileOut, finalCode, 'utf8' );
}
Compress the ajax-1.0.js I wrote and output it to the myApp directory
buildOne('ajax-1.0.js', 'ajax-min.js');