The Kotlin-Js Interop is a feature of Kotlin/JS that allows the use of JavaScript libraries in Kotlin code and vice versa.
Module: js-to-kotlin
Javascript | Kotlin |
To use npm dependencies in Kotlin/JS,
the dependencies must be added to the dependencies
block of the build.gradle.kts
file.
dependencies {
// Install npm dependencies
implementation(npm("randomstring", "1.3.0"))
}
And then define the exported function according to the JavaScript library's API.
Javascript | Kotlin |
var randomstring = require("randomstring");
randomstring.generate();
// >> "XwPp9xazJ0ku5CZnlmgAx2Dld8SHkAeT"
randomstring.generate(7);
// >> "xqm5wXX" |
@JsModule("randomstring")
@JsNonModule
external object RandomStringFromNpm {
fun generate(
length: Int = definedExternally,
): String
} |
Tip
To delegate default parameter value to the imported JavaScript function, use definedExternally
.
# from root
cd js-to-kotlin/kotlin-app
./gradlew cleanAllTests allTests --rerun-tasks
Module: kotlin-to-js
Kotlin | Javascript |
- Execute the perl script to link local npm packages in this project.
- Run the tests:
# from root cd kotlin-to-js/js-app npm test