Hello, I’ve been using Kotlin to develop a small 2D simulation software, and I’m using Kotlin multiplatform projects to make it run on both the JVM and in a browser. So far it works well.
However, I have a problem when I want to call functions defined in Kotlin/JS from regular Javascript.
To make my application work in the browser, I’m including the big JS file which is under the “build/distributions” folder after running the “build” Gradle task. When my Kotlin/JS application contains a main() function, this one is automatically being called when the HTML page is opened and it works well.
But if I remove the main function and instead I create a start() function which is supposed to be called manually (after a click on a button), it does not work: it says the function start() is not defined even though it is declared in the Kotlin code.
After opening the generated JS file it seems that indeed there is no start() function. It looks like all the name of the functions have been minified.
I tried adding @JsName, but it didn’t change anything.
So I guess I’m doing something wrong, but I really don’t know what and how to make it work.
You should call the function with module name and qualified name:
https://kotlinlang.org/docs/reference/js-to-kotlin-interop.html#package-structure
package my.qualified.packagename
fun foo() = "Hello"
alert(myModule.my.qualified.packagename.foo());
https://kotlinlang.org/docs/reference/js-to-kotlin-interop.html#jsname-annotation
In some cases (for example, to support overloads), Kotlin compiler mangles names of generated functions and attributes in JavaScript code. To control the generated names, you can use the @JsName
annotation
If it doesn’t help please attach your code or link to your project.
I am experiencing the same behavior and it’s very easy to reproduce.
Using the following setup, run the browserDevelopmentRun
Gradle task. Observe that it doesn’t work.
Now build the directory manually:
- uncomment the extra script tag
- copy kjs.js from build/js/packages/kjs/kotlin/kjs.js
- copy kotlin.js from build/js/packages_imported/kotlin/1.3.70-eap-184/kotlin.js
open the index.html file in a browser. Observe that it does work.
src/main/kotlin/main.kt
fun main() {
println("hello")
}
src/main/resources/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>kjs</title>
<!-- this is needed for the separate files version -->
<!-- <script src="kotlin.js"></script> -->
<script src="kjs.js"></script>
</head>
<body>
<input type="button" onClick="kjs.main()" value="click me"></input>
</body>
</html>
Can you attach a link to this sample project?
This appears to be fixed on the latest kotlin version 1.3.70-eap-274.
Unfortunately, I can’t reproduce the problem. It would be very helpful if you would attach your project.
Oh, sorry, I misunderstood you. But it still would be helpful if you attach your project because I want to reproduce the problem.