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.
Kotlin for JavaScript Kotlin/JS provides the ability to transpile your Kotlin code, the Kotlin standard library, and any compatible dependencies to JavaScript. The current implementation of Kotlin/JS targets ES5.
Users can use already existing modules on the client side JavaScript application without having to use a server. But how can this be done? Well, here comes a tool called Browserify. Browserify is a command line NodeJS module that allows users to write and use already existing NodeJS modules that run on the browser.
js Gradle plugin that provides project configuration tools together with helper tasks for automating routines typical for JavaScript development. For example, the plugin downloads the Yarn package manager for managing npm dependencies in background and can build a JavaScript bundle from a Kotlin project using webpack.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With