我最近使用Dojo toolkit构建了一个项目,并且非常喜欢如何将一段代码标记为仅包含在基于任意conditional check的编译版本中。我用它来导出私有变量进行单元测试或抛出错误而不是记录它们。这是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。
答案 0 :(得分: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']);
答案 1 :(得分:3)
Closure Compiler支持“定义”,如下所示:
/** @define {boolean} */
var CHANGABLE_ON_THE_COMMAND_LINE = false;