8

我最近使用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;
    }
  };
})();

编辑

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

4

2 回答 2

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']);
于 2011-05-05T21:52:44.203 回答
3

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

/** @define {boolean} */
var CHANGABLE_ON_THE_COMMAND_LINE = false;
于 2011-05-05T19:46:56.063 回答