Can someone please point me to any working example...
# javascript
g
Can someone please point me to any working examples that demonstrate Use JavaScript code from Kotlin. I am interested more on the code that interacts with external NPM packages, similar to the one in this blog post: JS in Kotlin/JS - DEV Community :woman::computer::man::computer: Most of the repos I see only has examples with React and I am not looking for those. Thanks.
r
KVision is one big example of interaction with lots of different NPM packages. You can check the code of different modules: https://github.com/rjaros/kvision/tree/master/kvision-modules
🙏 1
j
Kvision is a nice code base. We definitely got some inspiration from that for integrating leaflet last year in our kotlin-js web project. We later switched to maplibre. We ended up using Fritz2. Basically, you have several ways of dealing with javascript. You can write (or generate) strongly typed stubs and label them with
external
. Generating these from typescript definitions is a bit of a mixed bag. It can work for simple libraries. Didn't work too well for us with maplibre. But manually writing them is not that hard once you figure it out. And you can use some of the generated code to get started. The alternate strategy is to just use the dynamic keyword, which only works in kotlin-js. Basically this just disables type checks and allows you to call whatever on javascript objects. Great if you know what you are doing and it will obviously result in run-time errors when you call something that doesn't exist. We tend to do this. It's less work and we isolate the places where we interface with javascript libraries pretty well. Finally, you can put bits of javascript in a string and execute them with the
js("....")
this then returns a dynamic. A few gotchas: • libraries that expect a simple javascript object don't accept kotlin objects. Even if they implement your interface that you marked up with external. To work around this, you can actually construct javascript objects from kotlin. • typescript has union types, kotlin does not. Generated type mappings for those tend to npt even compile • make sure you understand how to work with co-routines and promises. You can convert one to the other. A lot of js apis expect or return promises.
v