Home > front end >  javascript as target in kotlin multiplatform library
javascript as target in kotlin multiplatform library

Time:08-27

I'm building a Kotlin multiplatform library. One of the targets in this project is javascript. In the source set I have added a dependency like this:

 val jsMain by getting {
        dependencies {
            implementation(npm("libphonenumber-js", "1.10.13"))
        }
    }

The gradle sync was successful, now I want to import the files in jsMain directory. How can I achieve this?

CodePudding user response:

You have to use js(IR) backend and generate externals implementation(npm("libphonenumber-js", "1.10.13", generateExternals = true)).

CodePudding user response:

  • Add npm dependency with generateExternals as you already did implementation(npm("libphonenumber-js", "1.10.13", generateExternals = true))

  • generateExternals = true triggers a tool called Screenshot of how external generated Kotlin code folder structure looks like

    (Ignore kmp-lib-1621 in above image. That would be your module/library name instead)`

    • Now copy and paste these files in your project (jsMain source set) and remove generateExternal = true from your dependency otherwise it would generate this files everytime. (1) you would lose any manual change (2) if you update the library version then it can potentially break your project

    You should be able to call generated external code from Kotlin code, whether you keep it in build folder or you pasted it in your project code.

    Important Note: Dukat tool is experiemental and known to create externals that may not work 100% times. So remove all unnecessary code from external generated code so you only end up having few references of classes you want to use from the npm library. Do some trial and error and you would be fine.

    Hope this helps!

  • Related