var result = UglifyJS.minify("/path/to/file.js");
console.log(result.code); // minified output
// if you need to pass code instead of file name
var result = UglifyJS.minify("var b = function () {};", {fromString: true});
var code = "function foo() {\n\
function x(){}\n\
function y(){}\n\
}\n\
function bar() {}";
var toplevel = UglifyJS.parse(code);
var walker = new UglifyJS.TreeWalker(function(node){
if (node instanceof UglifyJS.AST_Defun) {
// string_template is a cute little function that UglifyJS uses for warnings
console.log(UglifyJS.string_template("Found function {name} at {line},{col}", {
name: node.name.name,
line: node.start.line,
col: node.start.col
}));
return true; // That's it!
}
});
toplevel.walk(walker);
之前一直使用Closure.jar来压缩JS代码,不过似乎在Node上大家更习惯用UglifyJS来完成压缩、扰码的工作。 何为UglifyJS,官方介绍是
一般使用UglifyJS来压缩代码的似乎不关心整个minify的流程到底是怎样的? 直接使用命令行或者如下代码来完成压缩
不过对于高级玩家,还有另一番玩法。UglifyJS提供了parse功能,主要作用就是将一段代码解析成一颗语法树ast,另外UglifyJS给你提供了
两个函数,这样一来,要对这颗树遍历一遍还是转换一遍,都随你了。(亲,不要太暴力哦~)
完整介绍可以猛击上边的两个链接,另外下边列出了在研读cmd-util/lib/ast.js时用到的几个点,
true
就行define
或者require
开头,如何获知define
或require
的参数?注:以上介绍还属皮毛知识,详细内容还请移步官网一探究竟UglifyJS。