Kotlin - How to import node packages?

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.

Upvotes: 6

Views: 5536

Answers (3)

Namnodorel
Namnodorel

Reputation: 385

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

Upvotes: 4

Jayson Minard
Jayson Minard

Reputation: 85996

Kotlin front-end Gradle plugin does just what you are asking.

You can add NPM dependencies to the Gradle build as:

kotlinFrontend {
    npm {
        dependency "style-loader" // production dependency
        devDependency "karma"     // development dependency
    } 
}

And there are even full stack examples using this.

If the library also has a Kotlin external declared you can import them as you would any Gradle dependency. Something like:

dependencies {
    compile "org.kotlin:kotlinx-thingy-js:1.0.0"
}

If you have the Typescript definitions available you can use TS2KT to generate externals as well and place those directly into your project. Some wrapper libraries exist out there that you can already find in Maven or Github repositories.

You should read the information about interoperating from Kotlin to JavaScript in the online reference guide for more information about how this all works.

Upvotes: 1

andylamax
andylamax

Reputation: 2073

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

Upvotes: 3

Related Questions