使用Closure Compiler简单优化从函数内部删除调试代码

Bri*_*kel 8 javascript minify google-closure-compiler

我正在寻找一种从函数中删除调试代码的方法,这样我就可以为闭包添加测试挂钩.我已经阅读了 Google Closure Compiler高级版:在编译时删除了代码块,并测试了删除调试代码的方法如下:

/** @define {boolean} */
var DEBUG = true;

if (DEBUG) {
    console.log('remove me');
}
Run Code Online (Sandbox Code Playgroud)

简单的优化--define='DEBUG=false'减少了这个var DEBUG=!1;.这同样适用于此:

/** @const */
var DEBUG = false;

if (DEBUG) {
    console.log('remove me');
}
Run Code Online (Sandbox Code Playgroud)

我遇到麻烦的地方是在函数中使用这个约定:

/** @const */
var DEBUG = false;

function logMe() {
    if (DEBUG) {
        console.log('remove me');
    }
}
Run Code Online (Sandbox Code Playgroud)

这减少到以下几点:

var DEBUG=!1;function logMe(){DEBUG&&console.log("remove me")};
Run Code Online (Sandbox Code Playgroud)

我希望它进一步减少到:

var DEBUG=!1;function logMe(){};
Run Code Online (Sandbox Code Playgroud)

有没有理由不按预期工作?我真的只是想找到一种清除方法来剥离调试代码,我还没准备好接受高级优化.

更新

Per @ John的回答,我实现了自己的编译器,并发现以下配置将从if (DEBUG) {}代码的内部和外部删除@define:

CompilerOptions options = new CompilerOptions();
CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);
//options.setInlineConstantVars(true);
options.setInlineVariables(CompilerOptions.Reach.ALL);
options.setDefineToBooleanLiteral("DEBUG", false);
Run Code Online (Sandbox Code Playgroud)

这适用于具有以下限制的单个文件:

  1. 这需要var DEBUG在每个文件中定义,这是不好的做法.
  2. 组合多个文件时,您只能拥有一个var DEBUG或者编译器无法围绕它进行优化.通过单独编译每个文件并合并它们可以避免这种情况.
  3. 因为该值是在文件的开头定义的,所以没有预先接收该值的灵活性.

我已经玩弄了var DEBUG从文件中删除所有定义并在执行之前将其注入源或extern 的想法,但我遇到了两个问题:

  • 在extern中定义它似乎什么都不做.
  • DEBUG未编译的代码中未定义会在浏览器中引发引用错误.

理想的选择是测试window.DEBUG,它不会引发参考错误.不幸的是,当注入/** @const */ var window = {}; /** @const */ window.DEBUG = false;工作在顶层,减少时if (window.DEBUG) {},如果放在一个函数中,优化实际上会被恢复.

除非其他编译器选项的作品,将真正意义的唯一的选择就是去window.DEBUG和编译注射前/** @const */ var DEBUG = false;对一个全球性的替换/\bwindow.DEBUG\b/DEBUG.有没有更好的办法?

ale*_*ian 0

var DEBUG = true;从代码中删除并将所有检查条件转换if (DEBUG)if (goog.DEBUG). 修改您的编译器选项以读取--define goog.DEBUG=false. 该goog变量内置于 Closure Library API 中,为编译器提供选项和标志。