Importation of JS functions in Kotlin

Dear all,

Is there any possibility to import some JS file (example.js) with function e.g:

function myFunction(p1, p2) {
return p1 * p2;
}

into Kotlin main function and using it like

fun main() {
myFunction(5,5)
}

or to import any other JS files and using their functions in the main function in the .kt file?

Thanks a lot

I found this, but it is not working if I try to change things dynamically. E.G. calling js(“something”), this “something” must be a non-changeable string. I need to use interpolation and this is not acceptable in js().

Any suggestion on how to do this?

Look at the external modifier. It is described in much detail in that documentation.

Yes, but still I can not do pretty much. (BTW, I am new in JS and Kotlin).

Can you, please, share some examples, ideas, something?

The first thing to learn about is JavaScript modules. You need to put your Javascript function into a Javascript module. However there are many different module standards in JavaScript. The first thing you should do is learning how to use them.

Search for tutorials describing JavaScript modules. Learn how to use them. Write your own small JavaScript project that imports JavaScript modules.

Once you have learned about JavaScript modules, you can search for Kotlin tutorials that describe how to use and import JavaScript modules into Kotlin code.

Hi alzomins,
did you then find a solution? I have the same problem, I don’t know how to invoke from my kotlin main activity a function that I have defined inside a .js file. I am a newbie to android studio. I don’t know how to import the .js file into the kotlin project I don’t know how to make my function visible from the kotlin code.
If you have already found a solution and can share it I would be very grateful.
Thanks, see you soon

1 Like

I am also learning kotlinjs and want to directly use a json and js file from resources at compile time.
Found method kotlinx.js.import and playing with this method now.
Currently, I can console the content of imported files using absolute path.
I think we need to configure webpack so the files are included in the build directory, then we can import using relative path.

kotlinx.js.import is similar to dynamic import in javascript, not what we want.

So if we want to import js/json files at compile time, here is the correct way:

@JsModule("path-to-your-file")
@JsNonModule
external val yourFile: dynamic

fun main() {
  console.log(yourFile)
}

I am continuing to find the way to use relative path, instead of absolute path for @JsModule()

My final solution Kotlin/JS import json file as json object at compile time (github.com)

Fixed the broken link: Kotlin/JS import json file as json object at compile time (github.com)