我的web项目中有2000多个JS文件需要格式化。我知道Google闭包编译器很擅长这样做,实际上我正在使用它来编写一个用于整个JS文件格式化的工具。我的要求是格式化的JS文件将在相同的位置替换原来的JS文件。
我编写了一个Java程序来查找web项目中的每个JS文件,当找到一个文件时,线程将负责执行命令
java -jar compiler.jar --js C:/project/xyz/abc.js --js_output_file C:/project/xyz/abc.js`
原始JS文件(abc.js)将被格式化。
但我发现这种方式不那么有效。问题是,我使用ExecutorService来运行线程,每个线程大约需要10秒来完成文件的格式化。因此,您可以想象完成2000多个文件需要多长时间。
下面是代码片段。
ExecutorService executor = Executors.newFixedThreadPool(10);
// ...
for(File jsFile : root.listFiles()) {
Runnable formatThread = new FormatThread(jsFilePath.getAbsolutePath());
//execute command "java -jar compiler.jar in run(), handled by ProcessBuilder
executor.execute(formatThread);
}
我已经尝试过增加线程池的大小,但是在程序启动后,CPU和内存很快就被消耗殆尽。
我的问题是
发布于 2016-12-14 13:03:31
通过命令行启动所有这些任务会产生巨大的开销,因为它还需要启动一个新的jvm。
但是,您可以从jar清单表单java代码中运行主类的main
方法(afaik com.google.javascript.jscomp.CommandLineRunner
):
for(File jsFile : root.listFiles()) {
Runnable formatThread = () -> com.google.javascript.jscomp.CommandLineRunner.main(new String[] {"--js", jsFilePath.getAbsolutePath(), "--js_output_file", jsFilePath.getAbsolutePath()}));
executor.execute(formatThread);
}
甚至可能有一种更有效的方法来调用API..。
编辑:
API最好以另一种方式调用。例如:
CompilerOptions options = new CompilerOptions();
CompilationLevel.ADVANCED_OPTIMIZATIONS.setOptionsForCompilationLevel(options);
options.setCheckGlobalThisLevel(CheckLevel.OFF);
options.setOutputCharset("utf-8");
com.google.javascript.jscomp.Compiler compiler = new com.google.javascript.jscomp.Compiler(System.err);
compiler.disableThreads();
compiler.compile(SourceFile.fromFile(externsFile),
SourceFile.fromFile(jsFile),
options);
String result = compiler.toSource();
// TODO: write result to file
https://stackoverflow.com/questions/41143064
复制相似问题