在现在的 web 开发中,代码压缩是个很重要的环节,及时现在带宽都整体提升,M 级别的文件和 K 级别的文件加载效果肯定是不一样的。尤其是每个人的开发习惯各不相同,变量名、回车、空格都影响了文件的大小,理论上我们应该为我们的 javascript 代码都加上混淆加密来优化网页加载速度
今天介绍下 Node 项目 UglifyJS2 来做 JS 压缩
UglifyJS2 是 UglifyJS 的改进版,作者在此基础上做了很多优化改进。
下载
全局命令行使用1
$ npm install -g uglify-js
项目中使用1
$ yarn add uglify-js
命令行使用
命令格式1
$ uglifyjs [input files] [options]
准备文件 example.js
1
2
3
4function add(first, second) {
return first + second;
}
console.log(add(1 + 2, 3 + 4))
输出压缩结果1
$ uglifyjs example.js
1 | function add(first,second){return first+second}console.log(add(1+2,3+4)); |
添加混淆1
$ uglifyjs example.js -m
1 | function add(d,n){return d+n}console.log(add(1+2,3+4)); |
对表达式进行计算并去掉无用方法名1
$ uglifyjs example.js -m -c --toplevel
1 | console.log(function(n,o){return n+o}(3,7)); |
输出到文件1
2$ uglifyjs example.js -m -c --toplevel -o example.min.js
# example.min.js ==> console.log(function(n,o){return n+o}(3,7));
通过上边这些简单操作,我们就已经可以把代码压缩很多,想想我们文件中几百行的代码吧。更多的参数请看文档
项目中使用
我们可以在 Node 项目中使用该工具压缩,可以使用 minify(code, options)
这个方法,code
可以是字符串、JSON等格式,options
需要的参数1
2
3
4
5
6var UglifyJS = require("uglify-js");
var code = "function add(first, second) { return first + second; }";
var result = UglifyJS.minify(code);
console.log(result.error); // runtime error, or `undefined` if( no error
console.log(result.code); // minified output: function add(n,d){return n+d}){}
使用 JSON 格式的话 key 为文件名,value 为代码1
2
3
4
5
6
7var code = {
"file1.js": "function add(first, second) { return first + second; }",
"file2.js": "console.log(add(1 + 2, 3 + 4));"
};
var result = UglifyJS.minify(code);
console.log(result.code);
// function add(d,n){return d+n}console.log(add(3,7));
使用参数1
2
3
4
5
6
7
8var code = {
"file1.js": "function add(first, second) { return first + second; }",
"file2.js": "console.log(add(1 + 2, 3 + 4));"
};
var options = { toplevel: true };
var result = UglifyJS.minify(code, options);
console.log(result.code);
// console.log(3+7);
读取文件1
2
3
4
5
6var fs = require('fs');
var code = fs.readFileSync("./example.js", "utf8");
var res = UglifyJS.minify(code);
console.log(res.code);
// function add(d,n){return d+n}console.log(add(3,7));
更多参数见文档
了解了上边这些,你已经可以在项目用起来了,再多做些练习吧,让压缩更得心应手。
