CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-jetbrains-kotlin--kotlin-compiler

The Kotlin compiler infrastructure providing JVM, JavaScript, and metadata compilation capabilities

Pending
Overview
Eval results
Files

js-wasm-compilation.mddocs/

JavaScript and WebAssembly Compilation

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.

Capabilities

K2JSCompiler

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?
}

JavaScript/WebAssembly Compiler Arguments

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 Configuration Keys

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 Configuration Keys

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>
}

Module System Support

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 Targets

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?
    }
}

JavaScript Analysis and Generation

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
}

Usage Examples

Basic JavaScript Compilation

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

WebAssembly Compilation

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)

Browser Module (ES6)

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)

AMD Module for RequireJS

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 */"
}

TypeScript Declarations Generation

val args = K2JSCompilerArguments().apply {
    freeArgs = listOf("src/")
    outputFile = "build/js/app.js"
    moduleKind = "commonjs"
    
    // Generate TypeScript declarations
    generateDts = true
    declarationsOutputDir = "build/types"
}

Incremental Compilation

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
}

Programmatic Configuration

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
)

Output File Structure

JavaScript Module Output

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 Map Integration

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 Output

WebAssembly compilation produces:

  • .wasm binary file
  • .js runtime support file (for JS target)
  • Optional debug information files

Error Handling

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:

  • MODULE_NOT_FOUND: Missing library dependencies
  • UNSUPPORTED_FEATURE: Kotlin features not supported on JS/WASM platforms
  • INVALID_MODULE_KIND: Unsupported module system specification
  • SOURCE_MAP_ERROR: Source map generation failures

Install with Tessl CLI

npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-compiler

docs

configuration.md

environment.md

index.md

js-wasm-compilation.md

jvm-compilation.md

message-handling.md

plugin-development.md

tile.json