The Kotlin compiler infrastructure providing JVM, JavaScript, and metadata compilation capabilities
—
Kotlin-to-JavaScript and Kotlin-to-WebAssembly compilation supporting multiple module systems, source map generation, and both browser and Node.js target environments. The compiler produces optimized JavaScript ES5/ES6 code and efficient WebAssembly binaries.
Main entry point for JavaScript and WebAssembly compilation with comprehensive configuration options for different deployment scenarios.
/**
* Kotlin to JavaScript/WebAssembly compiler implementation
* Supports multiple JavaScript module systems and WebAssembly target
*/
class K2JSCompiler : CLICompiler<K2JSCompilerArguments>() {
override val platform: TargetPlatform // JsPlatforms.defaultJsPlatform
override fun createArguments(): K2JSCompilerArguments
override fun doExecute(
arguments: K2JSCompilerArguments,
configuration: CompilerConfiguration,
rootDisposable: Disposable,
paths: KotlinPaths?
): ExitCode
override fun doExecutePhased(
arguments: K2JSCompilerArguments,
services: Services,
messageCollector: MessageCollector
): ExitCode?
}Configuration arguments for JavaScript and WebAssembly compilation including module systems, optimization, and source mapping.
/**
* Arguments specific to JavaScript and WebAssembly compilation
* Supports various module systems and output formats
*/
class K2JSCompilerArguments : K2WasmCompilerArguments() {
/** Output file path for generated JavaScript */
var outputFile: String?
/** Output directory for multiple file output */
var outputDir: String?
/** JavaScript module system (amd, commonjs, plain, umd, es) */
var moduleKind: String?
/** Generate source maps for debugging */
var sourceMap: Boolean
/** Embed source code in source maps */
var sourceMapEmbedSources: String?
/** Base directory prefix for source map paths */
var sourceMapPrefix: String?
/** Names of source map paths */
var sourceMapBaseDirs: String?
/** Library files for compilation classpath */
var libraries: String?
/** Main function call mode (call, noCall) */
var main: String?
/** Output prefix for generated code */
var outputPrefix: String?
/** Output postfix for generated code */
var outputPostfix: String?
/** Target for compilation (js, wasm) */
var target: String?
/** Produce executable for WebAssembly */
var wasmProduceExecutable: Boolean
/** Debug information for WebAssembly */
var wasmDebugInfo: Boolean
/** Generate declarations (.d.ts files) */
var generateDts: Boolean
/** TypeScript declarations output directory */
var declarationsOutputDir: String?
/** Friend modules with access to internal declarations */
var friendModules: String?
/** Metadata directories */
var metadataOutputDir: String?
/** Cache directory for incremental compilation */
var cacheDirectory: String?
/** Use FIR (K2) frontend */
var useFir: Boolean
}JavaScript-specific configuration keys for detailed compilation control.
object JSConfigurationKeys {
/** Output file for generated JavaScript */
val OUTPUT_FILE: CompilerConfigurationKey<String>
/** Output directory for generated files */
val OUTPUT_DIR: CompilerConfigurationKey<File>
/** JavaScript module kind */
val MODULE_KIND: CompilerConfigurationKey<ModuleKind>
/** Generate source maps */
val SOURCE_MAP: CompilerConfigurationKey<Boolean>
/** Embed sources in source maps */
val SOURCE_MAP_EMBED_SOURCES: CompilerConfigurationKey<SourceMapEmbedSources>
/** Source map prefix */
val SOURCE_MAP_PREFIX: CompilerConfigurationKey<String>
/** Library files */
val LIBRARIES: CompilerConfigurationKey<List<String>>
/** Main call parameters */
val MAIN: CompilerConfigurationKey<String>
/** Pretty print generated code */
val PRETTY_PRINT: CompilerConfigurationKey<Boolean>
/** Minify generated code */
val MINIFY: CompilerConfigurationKey<Boolean>
}WebAssembly-specific configuration keys for WASM compilation.
object WasmConfigurationKeys {
/** WebAssembly target (js, d8, node) */
val WASM_TARGET: CompilerConfigurationKey<WasmTarget>
/** Produce executable WASM binary */
val PRODUCE_EXECUTABLE: CompilerConfigurationKey<Boolean>
/** Generate debug information */
val DEBUG_INFO: CompilerConfigurationKey<Boolean>
/** Optimization level */
val OPTIMIZATION_LEVEL: CompilerConfigurationKey<Int>
/** Use new exception handling */
val USE_NEW_EXCEPTION_HANDLING: CompilerConfigurationKey<Boolean>
}JavaScript module system definitions for different deployment targets.
enum class ModuleKind(val optionName: String, val fileExtension: String) {
PLAIN("plain", "js"),
AMD("amd", "js"),
COMMON_JS("commonjs", "js"),
UMD("umd", "js"),
ES("es", "mjs");
companion object {
fun fromString(string: String): ModuleKind?
}
}
enum class SourceMapEmbedSources {
NEVER, ALWAYS, INLINING;
companion object {
fun fromString(string: String?): SourceMapEmbedSources?
}
}WebAssembly compilation targets for different runtime environments.
enum class WasmTarget(val optionName: String) {
JS("js"),
D8("d8"),
NODE_JS("nodejs");
companion object {
fun fromString(string: String): WasmTarget?
}
}Core JavaScript compilation infrastructure for analysis and code generation.
/**
* JavaScript analysis result containing resolved modules and dependencies
*/
class JsAnalysisResult(
val moduleDescriptor: ModuleDescriptor,
val bindingContext: BindingContext,
val moduleSourceInfoMap: Map<KtFile, ModuleSourceInfo>
)
/**
* JavaScript IR compilation backend
* Transforms Kotlin IR to JavaScript code
*/
object JsIrBackend {
fun compileToJs(
depsDescriptors: ModulesStructure,
phaseConfig: PhaseConfig,
irFactory: IrFactory,
exportedDeclarations: Set<FqName> = emptySet(),
propertyLazyInitialization: Boolean = true
): CompilerResult
}import org.jetbrains.kotlin.cli.js.K2JSCompiler
import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments
import org.jetbrains.kotlin.cli.common.ExitCode
// Configure JavaScript compilation
val args = K2JSCompilerArguments().apply {
// Source files
freeArgs = listOf("src/main/kotlin")
// Output file
outputFile = "build/js/app.js"
// Module system for Node.js
moduleKind = "commonjs"
// Generate source maps for debugging
sourceMap = true
sourceMapEmbedSources = "always"
// Include Kotlin standard library
libraries = "lib/kotlin-stdlib-js.jar"
// Call main function
main = "call"
}
// Compile to JavaScript
val compiler = K2JSCompiler()
val exitCode = compiler.exec(System.err, Services.EMPTY, args)
if (exitCode == ExitCode.OK) {
println("JavaScript compilation successful")
}val args = K2JSCompilerArguments().apply {
freeArgs = listOf("src/main/kotlin")
outputFile = "build/wasm/app.wasm"
target = "wasm"
wasmProduceExecutable = true
wasmDebugInfo = true
libraries = "lib/kotlin-stdlib-wasm.jar"
}
val compiler = K2JSCompiler()
val result = compiler.exec(System.err, Services.EMPTY, args)val args = K2JSCompilerArguments().apply {
freeArgs = listOf("src/")
outputFile = "dist/app.mjs"
moduleKind = "es"
sourceMap = true
sourceMapPrefix = "../src/"
main = "noCall" // Don't auto-call main for library
}
val compiler = K2JSCompiler()
compiler.exec(System.err, Services.EMPTY, args)val args = K2JSCompilerArguments().apply {
freeArgs = listOf("src/main/kotlin/")
outputFile = "build/js/modules/myapp.js"
moduleKind = "amd"
sourceMap = true
libraries = "lib/kotlin-stdlib-js.jar:lib/kotlinx-coroutines-js.jar"
// Prefix and postfix for custom wrapping
outputPrefix = "/* Custom header */"
outputPostfix = "/* Custom footer */"
}val args = K2JSCompilerArguments().apply {
freeArgs = listOf("src/")
outputFile = "build/js/app.js"
moduleKind = "commonjs"
// Generate TypeScript declarations
generateDts = true
declarationsOutputDir = "build/types"
}val args = K2JSCompilerArguments().apply {
freeArgs = listOf("src/")
outputFile = "build/js/app.js"
moduleKind = "commonjs"
// Enable incremental compilation
cacheDirectory = "build/kotlin-js-cache"
useFir = true // Use K2 frontend for better performance
}import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.js.config.JSConfigurationKeys
import org.jetbrains.kotlin.js.config.ModuleKind
val configuration = CompilerConfiguration().apply {
put(JSConfigurationKeys.OUTPUT_FILE, "app.js")
put(JSConfigurationKeys.MODULE_KIND, ModuleKind.COMMON_JS)
put(JSConfigurationKeys.SOURCE_MAP, true)
put(JSConfigurationKeys.LIBRARIES, listOf("kotlin-stdlib-js.jar"))
put(JSConfigurationKeys.PRETTY_PRINT, false)
put(JSConfigurationKeys.MINIFY, true)
}
// Create environment and compile
val environment = KotlinCoreEnvironment.createForProduction(
parentDisposable = Disposer.newDisposable(),
configuration = configuration,
configFiles = EnvironmentConfigFiles.JS_CONFIG_FILES
)Generated JavaScript follows the specified module system format:
CommonJS Example:
// Generated from Kotlin sources
(function (root, factory) {
if (typeof exports === 'object') {
module.exports = factory(require('kotlin'));
}
// ... other module system support
})(this, function (kotlin) {
'use strict';
var _ = {
// Kotlin runtime integration
};
// Your compiled Kotlin code
function main() {
console.log('Hello from Kotlin!');
}
return {
main: main
};
});Source maps provide debugging support mapping generated JavaScript back to original Kotlin sources:
{
"version": 3,
"file": "app.js",
"sourceRoot": "",
"sources": ["../src/main/kotlin/Main.kt"],
"names": [],
"mappings": "AAAA,SAAS..."
}WebAssembly compilation produces:
.wasm binary file.js runtime support file (for JS target)JavaScript and WebAssembly compilation specific error handling:
class JsCompilerException(message: String, cause: Throwable? = null) : Exception(message, cause)
class UnsupportedFeatureException(message: String) : Exception(message)Common error scenarios:
Install with Tessl CLI
npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-compiler