Richik SC
Richik SC

Reputation: 884

Consume Kotlin Multiplatform Library in vanilla JS web app

I have a Kotlin multiplatform library that targets Kotlin/JVM and Kotlin/JS (Browser) containing some domain classes and business logic that needs to be shared across both frontend and backend. Consuming the multiplatform library as a simple Gradle/Maven dependency in the Java-based backend project was relatively easy and flawless. However, I'd like to write the frontend in plain Javascript or Typescript (not Kotlin) but call methods and classes in the Kotlin multiplatform library (which I have built for JS as well). Is this possible, and how would I do it?

Upvotes: 3

Views: 581

Answers (1)

Michael J
Michael J

Reputation: 46

The below configuration in build.gradle.kts worked for me:

kotlin {
    js(LEGACY) {
        browser {
            webpackTask {
                outputFileName = "myLibrary.js"
                output.library = "myLibrary"
                output.libraryTarget = "var"
            }
        }
        binaries.executable()
    }
}

It appears that the [output.library][1] and [output.libraryTarget][2] map to their corresponding Webpack configuration values. The Webpack documentation says that setting output.libraryTarget = "var" will expose the module as a variable in the global scope. output.library = "myLibrary" indicates that the global variable will be named myLibrary.

The library can then be imported via a script tag in the project's index.html file, e.g.:

<!DOCTYPE html>

<html>
<body>

<script type="text/javascript" src="path/to/myProject.js"></script>

</body>
</html>

Calling a library function is then done with fully qualified package names within the global object that was created, e.g.:

myLibrary.com.my.library.doStuff()

I hope that helps!

Upvotes: 1

Related Questions