Skip to content

Latest commit

 

History

History
140 lines (103 loc) · 2.88 KB

README.md

File metadata and controls

140 lines (103 loc) · 2.88 KB

Kotlin-Js Interop

The Kotlin-Js Interop is a feature of Kotlin/JS that allows the use of JavaScript libraries in Kotlin code and vice versa.

Table of Contents

Javascript to Kotlin

Module: js-to-kotlin

Demonstrations

Javascript Kotlin

src

jsMain
jsTest

NPM Dependencies

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.

Build and Run

# from root
cd js-to-kotlin/kotlin-app
./gradlew cleanAllTests allTests --rerun-tasks

Kotlin to Javascript

Module: kotlin-to-js

Demonstration

Kotlin Javascript

src

js-test

Build and Run

  1. Execute the perl script to link local npm packages in this project.
  2. Run the tests:
    # from root
    cd kotlin-to-js/js-app
    npm test

References