Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 compiled 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.

like image 981
SavoryBytes Avatar asked May 05 '11 15:05

SavoryBytes


2 Answers

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']);
like image 159
SavoryBytes Avatar answered Sep 22 '22 10:09

SavoryBytes


Closure Compiler supports "defines", like this:

/** @define {boolean} */
var CHANGABLE_ON_THE_COMMAND_LINE = false;
like image 45
John Avatar answered Sep 23 '22 10:09

John