【发布时间】:2012-06-09 07:13:05
【问题描述】:
尝试为我的 js 库准备良好的构建环境。根据网络上的评论,UglifyJS 似乎是最好的压缩模块之一,在 NodeJS 下工作。所以这里是压缩代码的最佳推荐方法:
var jsp = require("uglify-js").parser;
var pro = require("uglify-js").uglify;
var orig_code = "... JS code here";
var ast = jsp.parse(orig_code); // 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 final_code = pro.gen_code(ast); // compressed code here
如此处所见,pro.ast_mangle(ast) 应该修改变量名,但事实并非如此。我从这个管道中得到的只是 javascript 代码,没有空格。起初我认为我的代码没有针对压缩进行优化,但后来我用Google Closure 进行了尝试,得到了相当大的压缩(变量名和所有内容都被破坏了)。
UglifyJS 专家,有什么提示我做错了吗?
更新:
实际代码太大,无法在此处引用,但即使是这样的 sn-p 也不会被破坏:
;(function(window, document, undefined) {
function o(id) {
if (typeof id !== 'string') {
return id;
}
return document.getElementById(id);
}
// ...
/** @namespace */
window.mOxie = o;
}(window, document));
这就是我得到的(我猜只有空格被剥离):
(function(window,document,undefined){function o(id){return typeof id!="string"?id:document.getElementById(id)}window.mOxie=window.o=o})(window,document)
【问题讨论】:
-
我认为如果您发布一小段代码以及您发现问题的结果会有所帮助。
-
我想也许我缺少一些选项。现在用小 sn-p 更新。显然它与我的环境有关?.. 虽然不确定从哪里开始调试它或者什么可能会影响 uglify-js 在请求时破坏的能力。
-
嗯,通过 UglifyJS 的网站,我得到了:
(function(a,b,c){function d(a){return typeof a!="string"?a:b.getElementById(a)}a.mOxie=a.o=d})(window,document)你确定你打开了正确的开关吗? -
如果我的问题中的 uglifyJS 调用代码打开了正确的开关,那么 - 是的:|
-
奇怪...我在网站上尝试过,也得到了很好的压缩代码。所以这是我这边的事情......但不知道是什么。我正在使用我的问题中的代码来调用它。
标签: javascript performance compression minify uglifyjs