开发者

Using Google Closure Compiler can you exclude a section of source code from the compiled version?

I recently built a project using the Dojo toolkit and loved how you can mark a section of code to only be included in the co开发者_高级运维mpiled version based on an arbitrary conditional check. I used this to export private variables for unit testing or to throw errors vs. logging them. Here's an example of the Dojo format, I'd love to know if there are any special directives like this for the 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;
    }
  };
})();

Edit

Closure the definitive guide mentions that you can extend the CommandLineRunner to add your own Checks and Optimizations that might be one way to do it. Plover looks promising as it supports custom-passes.


This simple test case worked. Compile with --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']);


Closure Compiler supports "defines", like this:

/** @define {boolean} */
var CHANGABLE_ON_THE_COMMAND_LINE = false;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜