Skip to content

Instantly share code, notes, and snippets.

@eriwen
Last active July 4, 2020 21:38
Show Gist options
  • Save eriwen/bc9933b1c93b42dfd541 to your computer and use it in GitHub Desktop.
Save eriwen/bc9933b1c93b42dfd541 to your computer and use it in GitHub Desktop.
Minify individual files with Google Closure Compiler using Gradle
repositories {
mavenCentral()
}
dependencies {
compile localGroovy()
compile gradleApi()
compile ('com.google.javascript:closure-compiler:v20151015') {
exclude module: 'junit'
}
}
package com.foo.bar
import com.google.javascript.jscomp.*
import org.gradle.api.GradleException
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.SourceTask
class ClosureMinifyTask extends SourceTask {
@OutputDirectory
def dest
File getDest() {
project.file(dest)
}
@TaskAction
void run() {
source.visit { visitDetail ->
if (visitDetail.directory) {
visitDetail.relativePath.getFile(getDest()).mkdir()
} else {
if (visitDetail.name.endsWith(".js")) {
Set<File> externsFiles = project.closure.externs ? project.closure.externs.files : [] as Set<File>
File targetFile = visitDetail.relativePath.replaceLastName(visitDetail.name.replace(".js", ".min.js")).getFile(getDest())
File sourceMapFile = visitDetail.relativePath.replaceLastName(visitDetail.name.replace(".js", ".js.map")).getFile(getDest())
minifyJsFile(visitDetail.file, externsFiles, targetFile, sourceMapFile, project.closure.compilerOptions, project.closure.warningLevel, project.closure.compilationLevel)
}
}
}
}
void minifyJsFile(
final File inputFile,
final Set<File> externsFiles,
final File outputFile,
final File sourceMap,
CompilerOptions options,
final String warningLevel,
final String compilationLevel
) {
options = options ?: new CompilerOptions()
options.setSourceMapOutputPath(sourceMap?.path)
Compiler compiler = new Compiler()
CompilationLevel.valueOf(compilationLevel).setOptionsForCompilationLevel(options)
WarningLevel level = WarningLevel.valueOf(warningLevel)
level.setOptionsForWarningLevel(options)
List<SourceFile> externs = CommandLineRunner.getDefaultExterns()
if (externsFiles.size()) {
externs.addAll(externsFiles.collect() { SourceFile.fromFile(it) })
}
List<SourceFile> inputs = new ArrayList<SourceFile>()
inputs.add(SourceFile.fromFile(inputFile))
Result result = compiler.compile(externs, inputs, options)
if (result.success) {
outputFile.write(compiler.toSource())
if (sourceMap) {
def sourceMapContent = new StringBuffer()
result.sourceMap.appendTo(sourceMapContent, outputFile.name)
sourceMap.write(sourceMapContent.toString())
}
} else {
String error = ""
result.errors.each {
error += "${it.sourceName}:${it.lineNumber} - ${it.description}\n"
}
throw new GradleException(error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment