The code in build. js calls the UglifyJS interface function to execute the compression task.
1. Go to github to download the latest UglifyJS. Two download Methods: If git is installed, go to the git console and use the following command
Git clone git: // github.com/mishoo/UglifyJS.git
Or use http to download the file and click zip to download the file. After decompression, the directory structure is as follows:
2. Create a project (folder) myApp and copy the uglify-js.js and lib directories to your project. As follows:
3. Create compress. js in myApp. The content is as follows:
Copy codeThe Code is as follows:
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 );
This code roughly refers to the fs module, which is the file module of node. Then, the two UglifyJS modules are used. The following is the UglifyJS compression process.
4. Open the command line and execute compress. js.
The console outputs the compressed code. Okay, that's easy.
5. In the node environment, 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 shown below:
Copy codeThe Code is as follows:
// Read an object 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.
Copy codeThe Code is as follows: buildOne ('ajax-1.0.js', 'ajax-min. js ');
Sample Code UglifyJS_test