18

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

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 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)
jayarjo
  • 16,124
  • 24
  • 94
  • 138
  • I think it'd help if you post a small sniplet of code and the results that you find problems with. – Stephen Chung Jun 09 '12 at 12:47
  • I thought maybe there was some option I was missing. Updated now with the small snippet. Obviously it is something with my environment?.. Although not sure where to start debugging it or what might be influencing uglify-js ability to mangle, when it is requested. – jayarjo Jun 10 '12 at 15:14
  • 1
    Well, through UglifyJS's web site, I got: `(function(a,b,c){function d(a){return typeof a!="string"?a:b.getElementById(a)}a.mOxie=a.o=d})(window,document)` Are you sure you turned on the right switches? – Stephen Chung Jun 11 '12 at 01:49
  • If the right switches are turned on by the uglifyJS invocation code from my question, then - yes :| – jayarjo Jun 11 '12 at 07:39
  • Weird... I tried it on the site and got nicely compressed code too. So it is something on my side... but no idea what. I'm using the code in my question to invoke it. – jayarjo Jun 11 '12 at 07:46

4 Answers4

19

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
jayarjo
  • 16,124
  • 24
  • 94
  • 138
11

By default uglify won't mangle toplevel names, maybe thats what you seen?

Try: -mt or --mangle-toplevel — mangle names in the toplevel scope too (by default we don’t do this).

axkibe
  • 2,787
  • 4
  • 19
  • 13
  • 1
    respecively ast = uglify.uglify.ast_mangle(ast, {toplevel: true}); – axkibe Jun 09 '12 at 11:42
  • 1
    All my code is encapsulated into anonymous self-invoking function. I updated my question with a snippet. And hint of how I could debug the situation? – jayarjo Jun 10 '12 at 15:17
  • toplevel is not working for me. still no mangling of variables. everything is in anonymous functions. nothing is available from the global scope. – Kokodoko Jul 02 '16 at 14:13
  • worked for me with the option **--toplevel** – Thomas Jan 05 '23 at 09:11
1

If you're using Uglify2, you can use TopLevel.figure_out_scope(). http://lisperator.net/uglifyjs/scope

If you're using Uglify1, it's a little more complicated. Here's some code I put together by modifying the code from Uglify's squeeze_more.js file:

function eachGlobalFunctionCall(ast, callback) {
  var w = uglify.uglify.ast_walker(),
      walk = w.walk,
      MAP = uglify.uglify.MAP,
      scope;

  function with_scope(s, cont) {
    var save = scope, ret;
    scope = s;
    ret = cont();
    scope = save;
    return ret;
  }

  function _lambda(name, args, body) {
    return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
  }

  w.with_walkers({
    "function": _lambda,
    "defun": _lambda,
    "toplevel": function(body) {
      return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
    },
    "call": function(expr, args) {
      var fnName = expr[1];

      if (!scope.has(fnName)) {    // <--- here's the important part
        callback(fnName, args, scope);
      }
    }
  }, function() {
    return walk(uglify.uglify.ast_add_scope(ast));
  });
}

This one above only works on global function calls, but it gives you a callback which is executed as the walker finds a call to an unknown (global) method.

For example, given the following input:

function foo () {
  bar(1);
  (function () {
    function bar() { }
    bar(2);
    (function () {
      bar(3);
    }());
  }());
}

It would find the call bar(1) but not bar(2) or bar(3).

nickf
  • 537,072
  • 198
  • 649
  • 721
0

Variables in global scope are available to any other script, so Uglify won't change them without special switch, in case you really need them to be visible. You can either use -mt/toplevel switch/setting, or, better, yet, stop polluting global scope and clearly indicate that you don't intend for those variables to be seen outside, but framing your code into anonymous self-invoking function that will serve as private scope.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
  • "framing your code into anonymous self-invoking function" that's what I do actually. Only one top level object is exposed. – jayarjo Jun 10 '12 at 15:06
  • 1
    Every variable in your example is an variable from outer, global scope. – Oleg V. Volkov Jun 10 '12 at 18:43
  • 1
    Yes, variables from outer scope are passed into the self-invoking anonymous function as arguments. Doesn't this make them available for mangling (inside the function)? – jayarjo Jun 11 '12 at 07:38