gpt4 book ai didi

javascript - 使用 Google Closure Compiler 和 Gradle 压缩 JavaScript

转载 作者:行者123 更新时间:2023-11-29 20:48:16 25 4
gpt4 key购买 nike

我有一个使用 Gradle 构建的小型 Java Web 应用程序,其中包含一些自定义的 vanilla JavaScript。我想使用 Google Closure Compiler 缩小自定义 JS 代码。

Closure Compiler 的所有文档似乎都围绕使用 CLI 或 JSON API 来缩小 JS。我更喜欢直接从 Gradle 中调用 Java API,例如复制任务。

我想避免

  • 节点解决方案
  • 调用 CLI 并使用 java -jar
  • 对 JSON API 的 HTTP 调用

This example已过时且不反射(reflect)最新的 Java API。 This question已经有好几年了,尽管大多数 API 调用看起来与当前的 Java API 相似。

有没有其他人直接使用 Google Closure Compiler Java API 从 Gradle 压缩 JavaScript?

最佳答案

我有一个可行的解决方案:

task processWebapp(type: Copy) {
from('src/main/webapp') {
include "**/*"
}
eachFile {
if (it.sourceName.endsWith('.js') && !it.sourceName.endsWith('.min.js')) {
it.exclude()
Reader reader = it.file.newReader()
String source = ""
try {
source = reader.readLines().join("\r\n")
} finally {
reader.close()
}

com.google.javascript.jscomp.Compiler compiler = new com.google.javascript.jscomp.Compiler(System.err)

CompilerOptions options = new CompilerOptions()
CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(
options)

SourceFile extern = SourceFile.fromCode("externs.js", "")

SourceFile input = SourceFile.fromCode(it.sourceName, source)

compiler.compile(extern, input, options)

String transpiled = compiler.toSource()

def directoryPath = it.relativePath - it.sourceName

File theDir = new File("build/resources/main/${directoryPath}")
if (!theDir.exists()) {
theDir.mkdirs()
}

PrintWriter writer = new PrintWriter("build/resources/main/${it.relativeSourcePath}", "UTF-8")
try {
writer.println(transpiled)
} finally {
writer.close()
}
}
}
destinationDir = file('build/resources/main')
}

此任务复制从 src/main/webappbuild/resources/main 的所有内容,同时转译(缩小)所有以 .js 结尾的文件>(但不以 .min.js 结尾)在途中。 Gradle 然后将这些资源打包并嵌入到生成的 jar 中。

希望这对使用 Google Closure Compiler 和 Gradle 的其他人有所帮助。

关于javascript - 使用 Google Closure Compiler 和 Gradle 压缩 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53340258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com