使用Google Closure Compiler删除调试代码

时间:2015-03-30 18:47:05

标签: javascript gruntjs gulp google-closure-compiler google-closure

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

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(DEBUG){ 记录('调试消息'); }

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

1 个答案:

答案 0 :(得分:0)

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

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

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