Uglify-js不会变换变量名 [英] Uglify-js doesn't mangle variable names

查看:988
本文介绍了Uglify-js不会变换变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试为我的js库准备好的构建环境。根据网络上的评论 UglifyJS 似乎是最好的压缩模块之一,在NodeJS下工作。所以这里是最好的推荐方式来缩小代码:

Trying to prepare good build environment for my js library. According to reviews on the web UglifyJS seems to be one of the best compressing modules out there, working under NodeJS. So here is best recommended way of minifying the code:

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 应该mangle变量名,但它不。所有我离开这个管道是javascript代码,没有空格。起初,我认为我的代码没有针对压缩进行优化,但后来我尝试了 Google Closure ,并得到了相当的压缩(带有变量名和一切)。

As seen here, pro.ast_mangle(ast) should mangle variable names, but it doesn't. All I get out of this pipe is javascript code, with no spaces. At first I thought that my code was not optimized for compression, but then I tried it with Google Closure and got quite a compression (with mangled variable names and everything).

UglifyJS专家,任何暗示我做错了什么?

UglifyJS experts, any hint to what I'm doing wrong?

UPDATE

实际代码太大,无法在此处引用,但即使像这样的代码段也不会出错:

Actual code is too large to reference here, but even a snippet like this doesn't get mangled:

;(function(window, document, undefined) {

    function o(id) {
        if (typeof id !== 'string') {
            return id;  
        }
        return document.getElementById(id);
    }   

    // ...

    /** @namespace */
    window.mOxie = o;

}(window, document));

这是我得到的(只有空格被剥离我猜):

This is what I get (only spaces get stripped I guess):

(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,否则它不会啃任何东西。像这样:

Ok, it seems that the latest version of Uglify JS requires mangle option to be explicitly passed as true, otherwise it won't mangle anything. Like this:

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

这篇关于Uglify-js不会变换变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆