Home > Web Front-end > JS Tutorial > body text

How to merge/compress JavaScript using UglifyJS_Basic knowledge

WBOY
Release: 2016-05-16 17:55:34
Original
1208 people have browsed it

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:

Copy the code The 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);

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

Copy the code The code is 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
Copy code The code is as follows:
buildOne('ajax-1.0.js', 'ajax-min.js');

Sample codeUglifyJS_test
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!