Mangle nested classes and variables with uglifyjs

前端 未结 5 1876
礼貌的吻别
礼貌的吻别 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:16

    I have been trying to use --mangle-props of UglifyJS2 and can tell you: 'it makes a mess'.

    As someone pointed out: 'Developer should decide what properties to mangle, not uglifyjs'

    I am approaching the problem using this options:

    --mangle-props
    --mangle-regexp="/_$/"
    

    The regex matches any property with a underscore at the end.

    You asked to mangle nested names in the root namespace. So, your code:

    (function() {
      var root = { api:{}, core:{}, names:{} };
    
      root.names.SOME_LONG_NAMED_CONST_='Angel';
    
      root.core.Person_ = function(name) { this.name = name };
    
      root.api.perform_ = function(param_for_api) {  }
    
      window.lib_name.perform = root.api.perform;
    })();
    

    Would result in this:

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

    Command: uglifyjs --beautify --mangle --mangle-props --mangle-regex="/_$/" -- file.js

    If you want to mangle first level of root namespace (api, core, names) just put a underscore on them (api_, core_, names_), you are in control ;)

    Just a side note: when you are mangling properties usable by other js files, you should mangle all files together with the same command, so the same identifier will be used over all files.

提交回复
热议问题