以库的形式调用closure compiler

本来是用命令行的方式调用google closure compiler,可是效率不如人意;于是网上查找了些资料,实践了一下。

import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.JSSourceFile;

public class CallCompile {
	public static String compile(String code) {
		Compiler compiler = new Compiler();
		CompilerOptions options = new CompilerOptions();
		CompilationLevel.ADVANCED_OPTIMIZATIONS.setOptionsForCompilationLevel(options);

		JSSourceFile external = JSSourceFile.fromCode("external.js", "");
		JSSourceFile primary = JSSourceFile.fromCode("primary.js", code);

		compiler.compile(external, primary, options);

		return compiler.toSource();
	}

	public static void main(String[] args) {
		System.out.println(compile("console.log('hello world.')"));
	}
}

编译执行命令


# Windows下
javac -cp ".;./compiler.jar" CallCompile.java
java -cp ".;./compiler.jar" CallCompile

# Linux下
javac -cp ".:./compiler.jar" CallCompile.java
java -cp ".:./compiler.jar" CallCompile

2014-04-07 20:18 更新

最新的closure compiler有所更新,示例代码修改成如下:

import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.SourceFile;

// import java.util.logging.Level;

public class Test {

	public static void main(String[] args) {
		// Compiler.setLoggingLevel(Level.OFF);
		Compiler compiler = new Compiler();
		CompilerOptions options = new CompilerOptions();
		CompilationLevel.ADVANCED_OPTIMIZATIONS.setOptionsForCompilationLevel(options);
		SourceFile extern = SourceFile.fromCode("extern", "");
		SourceFile primary = SourceFile.fromCode("primary", "(function(){console.log('test')})();");
		compiler.compile(extern, primary, options);
		System.out.println(compiler.toSource());
		System.exit(0);
	}
}

标签: none

已有 2 条评论

  1. chelsea chelsea

    Compiler compiler = new Compiler();
    这一行在linux下无法通过,windows下没有问题.

    1. 可通过,我就是在centos下面的;你是不是忘了classpath了

添加新评论