Is it possible to use the Google Closure Compiler to minify Kotlin JS code further than what Webpack offers? If so, how can it be done?
1 Answer
First, you should declare an NPM dependency on the Closure Compiler (latest version):
dependencies {
implementation(devNpm("google-closure-compiler", "20210808.0.0"))
}
Then, create a task that will run after webpack minification:
tasks.create<Exec>("compileWithClosure") {
// browserProductionWebpack: production minified version by Webpack
// kotlinNodeJsSetup: needed to execute Node scripts (':' because it is on the root project)
dependsOn("browserProductionWebpack", ":kotlinNodeJsSetup")
// Get the Node installation directory
val kotlinNodeJsSetup = rootProject.tasks["kotlinNodeJsSetup"] as org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsSetupTask
workingDir = File(kotlinNodeJsSetup.destination, "bin")
// Execute the script
commandLine(
"node",
"${File(rootProject.buildDir, "js/node_modules/google-closure-compiler/cli.js")}",
"--js=${File(buildDir, "distributions/<your module name here>.js")}",
"--js_output_file=${File(buildDir, "distributions/optimized.js")}",
"-O=SIMPLE",
"--env=BROWSER",
"--warning_level=QUIET",
)
}
-O=ADVANCEDseems to break the Kotlin generated file (at least in my case with Kotlin JS 1.5.21 IR)-O=SIMPLEremoves ~600kB from the binary (2.1MB → 1.5MB, using Kotlin React, KotlinX.Serialization & Ktor)--warning_level=QUIETbecause we are passing an already-minified file, console output is completely unreadable, and actually slows down compilation