Mangle nested classes and variables with uglifyjs

前端 未结 5 1872
礼貌的吻别
礼貌的吻别 2021-01-05 08:26

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

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-05 09:07

    as @Jan-Misker explained in his answer, property name mangling is NOT an good idea because it could potentially break your code.

    However, you can workaround it by define the property names as local variables, and modify all .properties to [keys], to make smaller file size:

    (function() {
      var API = 'api';
      var CORE = 'core';
      var NAMES = 'names';
      var SLNC = 'SOME_LONG_NAMED_CONST';
    
      var root = {};
      root[API]={};
      root[CORE]={};
      root[NAMES]={};
    
      /* util.js file */
      root[NAMES][SLNC] ='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;
    
    })();
    

    Because now all the properties became a local variable, uglify js will mangle/shorten the variable names and as consequence you overall file size reduced:

    !function(){var a="api",b="core",c="names",d="SOME_LONG_NAMED_CONST",e={};e[a]={},e[b]={},e[c]={},e[c][d]="Angel",e[b].Person=function(a){this.name=a},e[a].perform=function(){},window.lib_name.perform=e[a].perform}();
    

    However, reduced file size doesn't mean you will get shorter downloading time on real server, because usually our http transport is gzipped, most of the repetitions will be compressed by your http server and it does a better job than human.

提交回复
热议问题