3

I need to generate uuid in Kotlin/JS and looking to call uuid.v4() from Kotlin/JS. I have gone through the documentation - https://kotlinlang.org/docs/using-packages-from-npm.html and https://kotlinlang.org/docs/js-modules.html but somehow cannot figure out how to invoke.

What I did is this -

  1. Included uuid as an npm dependency in JsMain sourceset
val jsMain by getting {
    dependencies {
        implementation(npm("uuid", "9.0.0"))
    }
}
  1. In JsMain, created a uuid.kt file with this content
@JsModule("uuid")
@JsNonModule
external fun v4(options: Any?, buf: Any?, offset: Any?): String
  1. In Kotlin/Js code, calling v4(null, null, null) doesn't works.

I get this error in console -

Uncaught ReferenceError: v4 is not defined
3
  • You need to mention the module using @JsModule("uuid") Commented Oct 13, 2022 at 13:26
  • Yeah, I forgot to mention in the question that I also added @JsModule("uuid"), edited the question... Commented Oct 14, 2022 at 14:42
  • Technically, this is a duplicate of Kotlin - How to import node packages?, but that question and its answers (more) outdated... Commented Jun 4 at 13:34

1 Answer 1

6

This is how it will work -

  1. declare uuid as an nmp dependency in JsMain sourceSet in build.gradle.kts
val jsMain by getting {
    dependencies {
        implementation(npm("uuid", "9.0.0"))
    }
}
  1. In JsMain, create a uuid.kt file with contents
@JsModule("uuid")
@JsNonModule
external val uuid: dynamic
  1. From Kotlin/Js, use it like
uuid.v4()
Sign up to request clarification or add additional context in comments.

2 Comments

Is this up-to-date? How does this relate to jsBrowserDevelopmentRun? How to make it aware of NPM dependencies?
It was working when I answered in '22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.