I want to use Closure Compiler to minify/compress JS code.
the problem is that it doesn't minify as well as I expect it to. consider the code below. when I pass the string
var func = function ( someArgument ) {
alert ( someArgument );
return someArgument;
}
I expect the minified code to rename "someArgument" to something much shorter, like "a".
is that the way it is or am I doing something wrong? TIA
public static void Compress( String src ) {
ByteArrayOutputStream err = new ByteArrayOutputStream();
CompilerOptions opt = new CompilerOptions();
CompilationLevel.ADVANCED_OPTIMIZATIONS.setDebugOptionsForCompilationLevel( opt );
Compiler.setLoggingLevel( Level.OFF );
Compiler compiler = new Compiler( new PrintStream( err ) );
compiler.disableThreads();
List<SourceFile> externs = Collections.emptyList();
List<SourceFile> inputs = Arrays.asList( SourceFile.fromCode( "javascript-code.js", src) );
Result result = compiler.compile( externs, inputs, opt );
System.out.println( "source: " + compiler.toSource() );
}
You are using
setDebugOptionsForCompilationLevel()
, you wantsetOptionsForCompilationLevel()
. From the Source this is whatsetDebugOptionsForCompilationLevel
is doing:While this is what
setOptionsForCompilationLevel()
is doing:Technically, SIMPLE_OPTIMIZATIONS would give you argument renaming., in case advanced start causing problems with your code (again from the source):