0

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 1

0

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",
    )
}

Full list of arguments:

  • -O=ADVANCED seems to break the Kotlin generated file (at least in my case with Kotlin JS 1.5.21 IR)
  • -O=SIMPLE removes ~600kB from the binary (2.1MB → 1.5MB, using Kotlin React, KotlinX.Serialization & Ktor)
  • --warning_level=QUIET because we are passing an already-minified file, console output is completely unreadable, and actually slows down compilation
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.