gpt4 book ai didi

javascript - Uglify-js 不会破坏变量名

转载 作者:可可西里 更新时间:2023-11-01 01:23:15 24 4
gpt4 key购买 nike

尝试为我的 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 专家,对我做错了什么有任何提示吗?

更新:

实际代码太大,无法在此处引用,但即使是这样的代码片段也不会被破坏:

;(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)

最佳答案

好吧,最新版本的 Uglify JS 似乎要求将 mangle 选项显式传递为 true,否则它不会 mangle 任何东西。像这样:

var jsp = require("uglify-js").parser;
var pro = require("uglify-js").uglify;

var orig_code = "... JS code here";
var options = {
mangle: true
};

var ast = jsp.parse(orig_code); // parse code and get the initial AST
ast = pro.ast_mangle(ast, options); // 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

关于javascript - Uglify-js 不会破坏变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10959154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com