or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdenvironment.mdindex.mdjs-wasm-compilation.mdjvm-compilation.mdmessage-handling.mdplugin-development.md

js-wasm-compilation.mddocs/

0

# JavaScript and WebAssembly Compilation

1

2

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.

3

4

## Capabilities

5

6

### K2JSCompiler

7

8

Main entry point for JavaScript and WebAssembly compilation with comprehensive configuration options for different deployment scenarios.

9

10

```kotlin { .api }

11

/**

12

* Kotlin to JavaScript/WebAssembly compiler implementation

13

* Supports multiple JavaScript module systems and WebAssembly target

14

*/

15

class K2JSCompiler : CLICompiler<K2JSCompilerArguments>() {

16

override val platform: TargetPlatform // JsPlatforms.defaultJsPlatform

17

18

override fun createArguments(): K2JSCompilerArguments

19

20

override fun doExecute(

21

arguments: K2JSCompilerArguments,

22

configuration: CompilerConfiguration,

23

rootDisposable: Disposable,

24

paths: KotlinPaths?

25

): ExitCode

26

27

override fun doExecutePhased(

28

arguments: K2JSCompilerArguments,

29

services: Services,

30

messageCollector: MessageCollector

31

): ExitCode?

32

}

33

```

34

35

### JavaScript/WebAssembly Compiler Arguments

36

37

Configuration arguments for JavaScript and WebAssembly compilation including module systems, optimization, and source mapping.

38

39

```kotlin { .api }

40

/**

41

* Arguments specific to JavaScript and WebAssembly compilation

42

* Supports various module systems and output formats

43

*/

44

class K2JSCompilerArguments : K2WasmCompilerArguments() {

45

/** Output file path for generated JavaScript */

46

var outputFile: String?

47

48

/** Output directory for multiple file output */

49

var outputDir: String?

50

51

/** JavaScript module system (amd, commonjs, plain, umd, es) */

52

var moduleKind: String?

53

54

/** Generate source maps for debugging */

55

var sourceMap: Boolean

56

57

/** Embed source code in source maps */

58

var sourceMapEmbedSources: String?

59

60

/** Base directory prefix for source map paths */

61

var sourceMapPrefix: String?

62

63

/** Names of source map paths */

64

var sourceMapBaseDirs: String?

65

66

/** Library files for compilation classpath */

67

var libraries: String?

68

69

/** Main function call mode (call, noCall) */

70

var main: String?

71

72

/** Output prefix for generated code */

73

var outputPrefix: String?

74

75

/** Output postfix for generated code */

76

var outputPostfix: String?

77

78

/** Target for compilation (js, wasm) */

79

var target: String?

80

81

/** Produce executable for WebAssembly */

82

var wasmProduceExecutable: Boolean

83

84

/** Debug information for WebAssembly */

85

var wasmDebugInfo: Boolean

86

87

/** Generate declarations (.d.ts files) */

88

var generateDts: Boolean

89

90

/** TypeScript declarations output directory */

91

var declarationsOutputDir: String?

92

93

/** Friend modules with access to internal declarations */

94

var friendModules: String?

95

96

/** Metadata directories */

97

var metadataOutputDir: String?

98

99

/** Cache directory for incremental compilation */

100

var cacheDirectory: String?

101

102

/** Use FIR (K2) frontend */

103

var useFir: Boolean

104

}

105

```

106

107

### JavaScript Configuration Keys

108

109

JavaScript-specific configuration keys for detailed compilation control.

110

111

```kotlin { .api }

112

object JSConfigurationKeys {

113

/** Output file for generated JavaScript */

114

val OUTPUT_FILE: CompilerConfigurationKey<String>

115

116

/** Output directory for generated files */

117

val OUTPUT_DIR: CompilerConfigurationKey<File>

118

119

/** JavaScript module kind */

120

val MODULE_KIND: CompilerConfigurationKey<ModuleKind>

121

122

/** Generate source maps */

123

val SOURCE_MAP: CompilerConfigurationKey<Boolean>

124

125

/** Embed sources in source maps */

126

val SOURCE_MAP_EMBED_SOURCES: CompilerConfigurationKey<SourceMapEmbedSources>

127

128

/** Source map prefix */

129

val SOURCE_MAP_PREFIX: CompilerConfigurationKey<String>

130

131

/** Library files */

132

val LIBRARIES: CompilerConfigurationKey<List<String>>

133

134

/** Main call parameters */

135

val MAIN: CompilerConfigurationKey<String>

136

137

/** Pretty print generated code */

138

val PRETTY_PRINT: CompilerConfigurationKey<Boolean>

139

140

/** Minify generated code */

141

val MINIFY: CompilerConfigurationKey<Boolean>

142

}

143

```

144

145

### WebAssembly Configuration Keys

146

147

WebAssembly-specific configuration keys for WASM compilation.

148

149

```kotlin { .api }

150

object WasmConfigurationKeys {

151

/** WebAssembly target (js, d8, node) */

152

val WASM_TARGET: CompilerConfigurationKey<WasmTarget>

153

154

/** Produce executable WASM binary */

155

val PRODUCE_EXECUTABLE: CompilerConfigurationKey<Boolean>

156

157

/** Generate debug information */

158

val DEBUG_INFO: CompilerConfigurationKey<Boolean>

159

160

/** Optimization level */

161

val OPTIMIZATION_LEVEL: CompilerConfigurationKey<Int>

162

163

/** Use new exception handling */

164

val USE_NEW_EXCEPTION_HANDLING: CompilerConfigurationKey<Boolean>

165

}

166

```

167

168

### Module System Support

169

170

JavaScript module system definitions for different deployment targets.

171

172

```kotlin { .api }

173

enum class ModuleKind(val optionName: String, val fileExtension: String) {

174

PLAIN("plain", "js"),

175

AMD("amd", "js"),

176

COMMON_JS("commonjs", "js"),

177

UMD("umd", "js"),

178

ES("es", "mjs");

179

180

companion object {

181

fun fromString(string: String): ModuleKind?

182

}

183

}

184

185

enum class SourceMapEmbedSources {

186

NEVER, ALWAYS, INLINING;

187

188

companion object {

189

fun fromString(string: String?): SourceMapEmbedSources?

190

}

191

}

192

```

193

194

### WebAssembly Targets

195

196

WebAssembly compilation targets for different runtime environments.

197

198

```kotlin { .api }

199

enum class WasmTarget(val optionName: String) {

200

JS("js"),

201

D8("d8"),

202

NODE_JS("nodejs");

203

204

companion object {

205

fun fromString(string: String): WasmTarget?

206

}

207

}

208

```

209

210

### JavaScript Analysis and Generation

211

212

Core JavaScript compilation infrastructure for analysis and code generation.

213

214

```kotlin { .api }

215

/**

216

* JavaScript analysis result containing resolved modules and dependencies

217

*/

218

class JsAnalysisResult(

219

val moduleDescriptor: ModuleDescriptor,

220

val bindingContext: BindingContext,

221

val moduleSourceInfoMap: Map<KtFile, ModuleSourceInfo>

222

)

223

224

/**

225

* JavaScript IR compilation backend

226

* Transforms Kotlin IR to JavaScript code

227

*/

228

object JsIrBackend {

229

fun compileToJs(

230

depsDescriptors: ModulesStructure,

231

phaseConfig: PhaseConfig,

232

irFactory: IrFactory,

233

exportedDeclarations: Set<FqName> = emptySet(),

234

propertyLazyInitialization: Boolean = true

235

): CompilerResult

236

}

237

```

238

239

## Usage Examples

240

241

### Basic JavaScript Compilation

242

243

```kotlin

244

import org.jetbrains.kotlin.cli.js.K2JSCompiler

245

import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments

246

import org.jetbrains.kotlin.cli.common.ExitCode

247

248

// Configure JavaScript compilation

249

val args = K2JSCompilerArguments().apply {

250

// Source files

251

freeArgs = listOf("src/main/kotlin")

252

253

// Output file

254

outputFile = "build/js/app.js"

255

256

// Module system for Node.js

257

moduleKind = "commonjs"

258

259

// Generate source maps for debugging

260

sourceMap = true

261

sourceMapEmbedSources = "always"

262

263

// Include Kotlin standard library

264

libraries = "lib/kotlin-stdlib-js.jar"

265

266

// Call main function

267

main = "call"

268

}

269

270

// Compile to JavaScript

271

val compiler = K2JSCompiler()

272

val exitCode = compiler.exec(System.err, Services.EMPTY, args)

273

274

if (exitCode == ExitCode.OK) {

275

println("JavaScript compilation successful")

276

}

277

```

278

279

### WebAssembly Compilation

280

281

```kotlin

282

val args = K2JSCompilerArguments().apply {

283

freeArgs = listOf("src/main/kotlin")

284

outputFile = "build/wasm/app.wasm"

285

target = "wasm"

286

wasmProduceExecutable = true

287

wasmDebugInfo = true

288

libraries = "lib/kotlin-stdlib-wasm.jar"

289

}

290

291

val compiler = K2JSCompiler()

292

val result = compiler.exec(System.err, Services.EMPTY, args)

293

```

294

295

### Browser Module (ES6)

296

297

```kotlin

298

val args = K2JSCompilerArguments().apply {

299

freeArgs = listOf("src/")

300

outputFile = "dist/app.mjs"

301

moduleKind = "es"

302

sourceMap = true

303

sourceMapPrefix = "../src/"

304

main = "noCall" // Don't auto-call main for library

305

}

306

307

val compiler = K2JSCompiler()

308

compiler.exec(System.err, Services.EMPTY, args)

309

```

310

311

### AMD Module for RequireJS

312

313

```kotlin

314

val args = K2JSCompilerArguments().apply {

315

freeArgs = listOf("src/main/kotlin/")

316

outputFile = "build/js/modules/myapp.js"

317

moduleKind = "amd"

318

sourceMap = true

319

libraries = "lib/kotlin-stdlib-js.jar:lib/kotlinx-coroutines-js.jar"

320

321

// Prefix and postfix for custom wrapping

322

outputPrefix = "/* Custom header */"

323

outputPostfix = "/* Custom footer */"

324

}

325

```

326

327

### TypeScript Declarations Generation

328

329

```kotlin

330

val args = K2JSCompilerArguments().apply {

331

freeArgs = listOf("src/")

332

outputFile = "build/js/app.js"

333

moduleKind = "commonjs"

334

335

// Generate TypeScript declarations

336

generateDts = true

337

declarationsOutputDir = "build/types"

338

}

339

```

340

341

### Incremental Compilation

342

343

```kotlin

344

val args = K2JSCompilerArguments().apply {

345

freeArgs = listOf("src/")

346

outputFile = "build/js/app.js"

347

moduleKind = "commonjs"

348

349

// Enable incremental compilation

350

cacheDirectory = "build/kotlin-js-cache"

351

useFir = true // Use K2 frontend for better performance

352

}

353

```

354

355

### Programmatic Configuration

356

357

```kotlin

358

import org.jetbrains.kotlin.config.CompilerConfiguration

359

import org.jetbrains.kotlin.js.config.JSConfigurationKeys

360

import org.jetbrains.kotlin.js.config.ModuleKind

361

362

val configuration = CompilerConfiguration().apply {

363

put(JSConfigurationKeys.OUTPUT_FILE, "app.js")

364

put(JSConfigurationKeys.MODULE_KIND, ModuleKind.COMMON_JS)

365

put(JSConfigurationKeys.SOURCE_MAP, true)

366

put(JSConfigurationKeys.LIBRARIES, listOf("kotlin-stdlib-js.jar"))

367

put(JSConfigurationKeys.PRETTY_PRINT, false)

368

put(JSConfigurationKeys.MINIFY, true)

369

}

370

371

// Create environment and compile

372

val environment = KotlinCoreEnvironment.createForProduction(

373

parentDisposable = Disposer.newDisposable(),

374

configuration = configuration,

375

configFiles = EnvironmentConfigFiles.JS_CONFIG_FILES

376

)

377

```

378

379

## Output File Structure

380

381

### JavaScript Module Output

382

383

Generated JavaScript follows the specified module system format:

384

385

**CommonJS Example:**

386

```javascript

387

// Generated from Kotlin sources

388

(function (root, factory) {

389

if (typeof exports === 'object') {

390

module.exports = factory(require('kotlin'));

391

}

392

// ... other module system support

393

})(this, function (kotlin) {

394

'use strict';

395

var _ = {

396

// Kotlin runtime integration

397

};

398

399

// Your compiled Kotlin code

400

function main() {

401

console.log('Hello from Kotlin!');

402

}

403

404

return {

405

main: main

406

};

407

});

408

```

409

410

### Source Map Integration

411

412

Source maps provide debugging support mapping generated JavaScript back to original Kotlin sources:

413

414

```json

415

{

416

"version": 3,

417

"file": "app.js",

418

"sourceRoot": "",

419

"sources": ["../src/main/kotlin/Main.kt"],

420

"names": [],

421

"mappings": "AAAA,SAAS..."

422

}

423

```

424

425

### WebAssembly Output

426

427

WebAssembly compilation produces:

428

- `.wasm` binary file

429

- `.js` runtime support file (for JS target)

430

- Optional debug information files

431

432

## Error Handling

433

434

JavaScript and WebAssembly compilation specific error handling:

435

436

```kotlin { .api }

437

class JsCompilerException(message: String, cause: Throwable? = null) : Exception(message, cause)

438

439

class UnsupportedFeatureException(message: String) : Exception(message)

440

```

441

442

Common error scenarios:

443

- **MODULE_NOT_FOUND**: Missing library dependencies

444

- **UNSUPPORTED_FEATURE**: Kotlin features not supported on JS/WASM platforms

445

- **INVALID_MODULE_KIND**: Unsupported module system specification

446

- **SOURCE_MAP_ERROR**: Source map generation failures