2011-05-05 18 views
8

我最近使用Dojo toolkit構建了一個項目,並且非常喜歡你如何標記一段代碼,以便只包含在基於任意conditional check的編譯版本中。我用這個來導出私有變量進行單元測試或者拋出錯誤與記錄它們。這裏有一個Dojo格式的例子,我很想知道Google Closure Compiler是否有這樣的特殊指令。使用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

+1

您是否知道可以在高級模式下使用Closure Compiler和Dojo Toolkit?查看我的文檔:http://dojo-toolkit.33424.n3.nabble.com/file/n2636749/Using_the_Dojo_Toolkit_with_the_Closure_Compiler.pdf?by-user=t – 2011-05-06 07:04:30

回答

3

關閉編譯器支持 「定義」,像這樣:

/** @define {boolean} */ 
var CHANGABLE_ON_THE_COMMAND_LINE = false; 
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']); 
+3

我相信這個答案比接受的答案更正確,因爲它使用一個內置的(雖然沒有記錄的)Closure選項,它更符合「正確」做事的方式。答案也更長,並且包括一個例子。 – 2011-08-12 11:00:59

+0

@LeeHambley,什麼?除了「漫長而模範」之外,這些答案在任何方面都有所不同?他們都給你'/ ** @define {布爾} * /'註釋。 – 2015-08-21 10:01:37

相關問題