Skip to content

Instantly share code, notes, and snippets.

@jabley
Created October 4, 2011 17:30
Show Gist options
  • Save jabley/1262250 to your computer and use it in GitHub Desktop.
Save jabley/1262250 to your computer and use it in GitHub Desktop.
Example of using the Google Closure Compiler at runtime
/*
* Copyright 2011 James Abley
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.JSSourceFile;
import com.google.javascript.jscomp.Result;
public class ClosureMinifier {
private final Reader input;
/**
* @param stringReader
*/
public ClosureMinifier(Reader input) {
this.input = input;
}
/**
* @return
*/
public Reader minify() throws IOException {
List<JSSourceFile> externs = Collections.emptyList();
List<JSSourceFile> inputs = Arrays.asList(JSSourceFile.fromCode("default.js",
getCodeFromReader()));
CompilerOptions options = new CompilerOptions();
CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);
com.google.javascript.jscomp.Compiler compiler = new com.google.javascript.jscomp.Compiler();
Result result = compiler.compile(externs, inputs, options);
if (result.success) {
return new StringReader(compiler.toSource());
}
throw new IllegalArgumentException("Unable to minify input source");
}
private String getCodeFromReader() throws IOException {
StringBuilder sb = new StringBuilder(10240);
int c;
while ((c = this.input.read()) != -1) {
sb.append((char) c);
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment