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:
var fs = require('fs');
var jsp = require("./uglify-js").parser;
var pro = require("./uglify-js"). uglify;
var origCode = "var abc = function(){ var one = 5; return one;}";
var ast = 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
var finalCode = pro .gen_code(ast); // compressed code here
console.log(finalCode);
The general meaning of this code is to get 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);
fs.writeFileSync(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');
Sample code
UglifyJS_test