The KotlinJsCompilation class allows you to programmatically run Kotlin/JS compilations. It extends AbstractKotlinCompilation and is designed to work with the IR backend.
Key configuration options include:
irProduceJs: (Default: true) Generates the JS file using the IR backend.irProduceKlibDir: Generates an unpacked KLIB into the parent directory of the output JS file.irProduceKlibFile: Generates a packed klib into the file specified by -output.irDce: Enables experimental dead code elimination.generateDts: Generates TypeScript .d.ts declarations alongside the JS file (IR backend only).moduleName / irModuleName: Specifies the compilation module name.kotlinStdLibJsJar: Path to kotlin-stdlib-js.jar. If not provided, it is searched for in the host process classpaths.
The resulting files (classes, jars, resources) are placed in the outputDir, which is a subdirectory named output within your workingDir.
To execute the compilation, call the compile() method, which returns a JsCompilationResult containing the exitCode, messages, and diagnostics.
val compilation = KotlinJsCompilation(
sources = listOf(sourceFile1, sourceFile2),
workingDir = File("build/test-compilation"),
inheritClassPath = true
).apply {
irProduceJs = true
generateDts = true
moduleName = "my-module"
}
val result = compilation.compile()
if (result.exitCode == KotlinCompilation.ExitCode.OK) {
println("Compilation successful!")
} else {
println("Compilation failed: ${result.messages}")
}