Kotlin - How to import node packages?

Viewed 3782

I am developing a web application using Kotlin to build its front-end.

I want to be able to import npm packages so I can use them in my Kotlin code. I can't find an example on how to do this. There are examples on how to generate npm packages from Kotlin, but not how to USE them in your Kotlin code.

I would also be happy if I could import Java libraries, use them in my Kotlin code and compile it down to JavaScript, but that does not seem to be possible yet, which is why I want to import npm code instead.

3 Answers

Since Kotlin 1.3.40 this works a little different. There is a new JavaScript plugin:

plugins {
    id("org.jetbrains.kotlin.js") version "1.3.40"
}

The old JavaScript Frontend plugin will be deprecated once all features have been ported to the new one.

With the new plugin comes a new (currently experimental) way of adding NPM dependencies:

dependencies {
    implementation(npm("react", "16.8.3"))
}

(Note: npm(...) only works with JavaScript sourcesets)

Kotlin 1.3.50 makes your life even easier by automatically generating Kotlin external headers for the libraries you use. This, too, is an experimental feature and needs to be turned on explicitly in your gradle.properties:

kotlin.js.experimental.generateKotlinExternals=true

assuming you'd want the equivalent of

import {Express} from "express"

you would do this in Kotlin

@JsModule("express")
external class Express // if Express is a class in its module

which means, if its a function you are looking for say

import {dollface} from "dolly"

you would define it in kotlin as

@JsModule("dolly")
external fun dollface(faceColor: String)

See more elaborations here

Related