CodeBlanks Logo Icon CodeBlanks

JS target

Learn the JavaScript target with KMP.

JS target

In KMP the JavaScript target compiles Kotlin code into a JavaScript module that runs in the browser or in Node.js.

The target is added in Gradle with the js() block. Inside it you choose the nodejs() (Node) or browser() (browser) environment. The output is a .js file; it can also be published as an npm package. The Kotlin stdlib is embedded into this file automatically. The jsTarget function in this lesson models the concept.

Using the JS module

The module produced by the JS target can be added to an HTML page with a <script> tag or called from Node.js with require.

In Gradle the js { browser { webpackTask { } } } block manages packaging. Kotlin functions marked with @JsExport become visible to JavaScript. This way shared logic runs both in the browser and in Node. Type mapping is automatic: Kotlin String maps to JS string.

Practice Write jsTarget

Define fun jsTarget(): String. It should return "JS". In main, write println(jsTarget()).

Starter code

Main.kt
// add the jsTarget function

fun main() {
    // print the JS target
}

Sample solution

Main.kt
fun jsTarget(): String = "JS"
fun main() {
    println(jsTarget())
}

Expected output

JS

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the js block

Question
____ {
    nodejs()
}
Answer
js {
    nodejs()
}

Explanation: The js() block adds the JavaScript target.

2 What does the js() block produce?

Main.kt
The JS output has a .js extension.
  • .jar
  • .framework
  • .js file Correct answer
  • .dylib

Explanation: The js() block produces a JavaScript file.

3 Match the JS parts

Term Meaning
js() Browser/Node target
nodejs() Node environment
browser() Browser environment
.js Output file

All lessons in Expert