使用Google Closure Compiler可以从编译版本中排除一部分源代码吗?

dan*_*lmb 8 javascript unit-testing google-closure-compiler

我最近使用Dojo工具包构建了一个项目,并且喜欢如何将一段代码标记为仅基于任意条件检查包含在编译版本中.我用它来导出私有变量进行单元测试或抛出错误而不是记录它们.这是Dojo格式的一个例子,我很想知道Google Closure Compiler是否有这样的特殊指令.

window.module = (function(){

  //private variable
  var bar = {hidden:"secret"};

  //>>excludeStart("DEBUG", true);
    //export internal variables for unit testing 
    window.bar = bar;
  //>>excludeEnd("DEBUG");

  //return privileged methods
  return {
    foo: function(val){
      bar.hidden = val;
    }
  };
})();
Run Code Online (Sandbox Code Playgroud)

编辑

关闭权威指南提到您可以扩展CommandLineRunner以添加您自己的检查和优化,这可能是一种方法.Plover看起来很有前途,因为它支持自定义传递.

dan*_*lmb 10

这个简单的测试案例有效.编译--define DEBUG=false

/**
 * @define {boolean} DEBUG is provided as a convenience so that debugging code
 * that should not be included in a production js_binary can be easily stripped
 * by specifying --define DEBUG=false to the JSCompiler. For example, most
 * toString() methods should be declared inside an "if (DEBUG)" conditional
 * because they are generally used for debugging purposes and it is difficult
 * for the JSCompiler to statically determine whether they are used.
 */
var DEBUG = true;

window['module'] = (function(){

  //private variable
  var bar = {hidden:"secret"};

  if (DEBUG) {
    //export internal variables for unit testing 
    window['bar'] = bar;
  }

  //return privileged methods
  return {
      foo: function(val){
        bar.hidden = val;
      }
  };
})();

console.log(window['bar']);
module.foo("update");
console.log(window['bar']);
Run Code Online (Sandbox Code Playgroud)

  • 我相信这个答案比接受的答案更正确,因为它使用了一个内置的(虽然没有记录)Closure选项,它更符合"正确"的做事方式.答案也更长,并包含一个例子. (3认同)

小智 3

闭包编译器支持“定义”,如下所示:

/** @define {boolean} */
var CHANGABLE_ON_THE_COMMAND_LINE = false;
Run Code Online (Sandbox Code Playgroud)