使用uglifyjs对嵌套的类和变量进行管理 [英] Mangle nested classes and variables with uglifyjs

查看:131
本文介绍了使用uglifyjs对嵌套的类和变量进行管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用uglifyjs来缩小连接的文件集,这种方法很好但不够好。构建的lib使用名称空间,因此类,函数和常量存储在根名称空间变量中:

I use uglifyjs to minify a concatenated set of files, which works fine but not good enough. The built lib uses namespaces, so classes, functions and constants are stored in a root namespace variable:

(function() {
  var root = { api:{}, core:{}, names:{} };

  /* util.js file */
  root.names.SOME_LONG_NAMED_CONST='Angel';

  /* Person.js file */
  root.core.Person = function(name) { this.name = name };

  /* API.js with the functions we want to expose */
  root.api.perform = function(param_for_api) { /* do something */ }

  window.lib_name.perform = root.api.perform;

})();

将其缩小为非最小版本

(function(){var a={api:{},core:{},names:{}};a.names.SOME_LONG_NAMED_CONST="Angel",a.core.Person=function(a){this.name=a},a.api.perform=function(){},window.lib_name.perform=a.api.perform})();

我理解uglify可能认为root var是一个必须按原样保存的数据结构不要改变。有没有办法让uglify破坏根命名空间中的嵌套名称?

I understand uglify probably thinks that root var is a data structure that must be kept as-is and can't be changed. Is there a way to let uglify mangle the nested names in the root namespace?

推荐答案

当您最小化Javascript时,您只能更改名称变量,api,核心和名称不是变量,而是对象的属性。如果最小化器改变了这些,您可能会得到意想不到的结果。如果在你的代码中你会打电话

When you minimize Javascript you can only change names of variables, the api, core and names are not variables but properties of an object. If these were changed by the minimizer, you would potentially get unexpected results. What if in your code you would call

root["api"].perform = function()...

甚至类似

function doIt(section, method, argument) {
    root[section][method](argument);
}
doIt('api','perform', 101);

所有完全合法的JS,但是最小化者永远无法弄清楚发生了什么。

All perfectly legal JS, but a minimizer could never figure out what's going on.

这篇关于使用uglifyjs对嵌套的类和变量进行管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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