Search code examples
javascriptgruntjsgulpgoogle-closure-compilergoogle-closure

Debug code removal using Google Closure Compiler


If I run the following code through advanced optimization, I can still see the debug statements in the code.

var log = console.info.bind(console);
  (function() {
       /** @const */
       var DEBUG = false;

       log('Brady', createRank({
           max: 100,
           debug: DEBUG
      }));
  })();
 function createRank(options) {
     if (options.debug) {
         log('This should be in debug mode only');
     }
     if(typeof alert == 'function'){
         alert(options);
     }
     return (Math.random() * options.max) | 0;
}

output after Advanced mode compilation

(function() {
      var a = console.info.bind(console),
            b = {
                max: 100,
                debug: !1
            };
       b.debug && a("This should be in debug mode only");
       "function" == typeof alert && alert(b);
       a("Brady", Math.random() * b.max | 0);
   })();

How can we get rid of debug message with advanced mode?

if the DEBUG variable is defined as global, and logging statements are enclosed like

if (DEBUG) { log('debug message'); }

then it would work but is there a way to make it work if we don't not want it as a global variable, and rather pass the value around to individual modules/functions via parameters.


Solution

  • This is a limitation of the current set of optimizations and when they are run. The optimizations are a trade off between compilation time and optimization and the choices made are not necessarily ideal for every code pattern.

    In this particular case, the issue is that "property collapsing" only happens once for global scope, and that is before function inlining occurs ("property collapsing" for objects local to a function occurs during the main optimization loop). For the code in your example to be removed, "collapse properties" would need to run at least once more, or the function local version (which is more conservative) would need to be enhanced to run in global scope.

    This is also discussed here: https://github.com/google/closure-compiler/issues/891