使用Google闭包编译器调试代码删除

Debug code removal using Google Closure Compiler

本文关键字:代码 码删除 调试 编译器 Google 闭包 使用      更新时间:2023-09-26

如果我通过高级优化运行以下代码,我仍然可以在代码中看到调试语句。

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;
}

高级模式编译后的输出

(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);
   })();

如何使用高级模式消除调试消息?

如果DEBUG变量被定义为全局变量,并且日志记录语句像一样被括起来

if(调试){日志("调试消息");}

那么它会起作用,但如果我们不希望它作为全局变量,而是通过参数将值传递给各个模块/函数,有没有办法让它起作用。

这是当前一组优化以及它们何时运行的限制。优化是编译时间和优化之间的权衡,所做的选择不一定适用于每种代码模式。

在这种特殊情况下,问题是全局作用域的"属性折叠"只发生一次,也就是在函数内联发生之前(函数本地对象的"属性崩溃"发生在主优化循环期间)。为了删除示例中的代码,"collapse properties"至少需要再次运行一次,或者需要增强函数本地版本(更保守)才能在全局范围内运行。

这里也讨论了这一点:https://github.com/google/closure-compiler/issues/891