Since version 1.1.4, Kotlin/JS includes a dead code elimination (DCE) tool. This tool allows to strip out unused properties, functions and classes from the generated JS. There are several ways you get unused declarations:
kotlin.js) contains functions for manipulating lists, arrays, char sequences, adapters for DOM, etc, which together gives about 1.3 mb file. A simple "Hello, world" application only requires console routines, which is only few kilobytes for the entire file.
Dead code elimination is often also called 'tree shaking'.
DCE tool is currently available from Gradle.
To activate DCE tool, add the following line to
apply plugin: 'kotlin-dce-js'
Note that if you are using multi-project build, you should apply plugin to the main project that is an entry point to your application.
To configure DCE on the main source set, you can use the
runDceKotlinJs task (and corresponding
runDce<sourceSetName>KotlinJs for other source sets).
runDceKotlinJs.keep "declarationToKeep"[, "declarationToKeep", ...]
declarationToKeep has the following syntax:
For example, consider a module is named
kotlin-js-example and it contains a function named
toKeep in package
org.jetbrains.kotlin.examples. Use the following line:
Note that if your function has parameters, its name will be mangled, so the mangled name should be used in the keep directive.
Running DCE takes a bit of extra time each build, and the output size does not matter during development. You can improve development builds time by making the DCE tool skip actual dead code elimination with the
dceOptions.devMode flag of the DCE tasks.
For example, to disable DCE based on a custom condition for the
main source set and always for the
test code, add the following lines to the build script:
runDceKotlinJs.dceOptions.devMode = isDevMode runDceTestKotlinJs.dceOptions.devMode = true
A full example that shows how to integrate Kotlin with DCE and webpack to get a small bundle, can be found here.
© 2010–2018 JetBrains s.r.o.
Licensed under the Apache License, Version 2.0.