This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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(); | |
} | |
} |
As part of a product that serves as a rendering runtime for mobile, this allows authors to create Javascript, and the runtime can optimise and cache on the fly. We like it!