Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Closure Compiler strip log function usages



I have a logging API I want to expose to some internal JS code. I want to be able to use this API to log, but only when I am making a debug build. Right now, I have it partially working. It only logs on debug builds, but the calls to this API are still in the code when there is a regular build. I would like the closure-compiler to remove this essentially dead code when I compiler with goog.DEBUG = false.

Log definition:

goog.provide('com.foo.android.Log');
com.foo.Log.e = function(message){
    goog.DEBUG && AndroidLog.e(message);
}
goog.export(com.foo.Log, "e", com.foo.Log.e);

AndroidLog is a Java object provided to the webview this will run in, and properly externed like this:

var AndroidLog = {};

/**
 * Log out to the error console
 * 
 * @param {string} message The message to log
 */
AndroidLog.e = function(message) {};

Then, in my code, I can use:

com.foo.Log.e("Hello!"); // I want these stripped in production builds

My question is this: How can I provide this API, use this API all over my code, but then have any calls to this API removed when not compiled with goog.DEBUG = true? Right now, my code base is getting bloated with a bunch of calls to the Log API that are never called. I want the removed.

Thanks!

like image 780
Sky Kelsey Avatar asked Mar 21 '12 00:03

Sky Kelsey


1 Answers

The Closure Compiler provides four options in CompilerOptions.java to strip code: 1) stripTypes, 2) stripNameSuffixes, 3) stripNamePrefixes and 4) stripTypePrefixes. The Closure build tool plovr, exposes stripNameSuffixes and stripTypePrefixes through its JSON configuration file options name-suffixes-to-strip and type-prefixes-to-strip.

There are excellent examples of how these options work in Closure: The Definitive Guide on pages 442 to 444. The following lines are provided as common use cases:

options.stripTypePrefixes = ImmutableSet.of(“goog.debug”, “goog.asserts”);
options.stripNameSuffixes = ImmutableSet.of(“logger”, “logger_”); 

To understand the nuances of these options and avoid potential pitfalls, I highly recommend reading the complete examples in Closure: The Definitive Guide.

like image 183
Christopher Peisert Avatar answered Sep 28 '22 11:09

Christopher Peisert