Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - How to import node packages?

Tags:

npm

kotlin

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.

like image 686
Bitcoin Cash - ADA enthusiast Avatar asked May 26 '17 01:05

Bitcoin Cash - ADA enthusiast


People also ask

Can kotlin compile to JavaScript?

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.

Can you use node packages in the browser?

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.

Can Gradle build JavaScript?

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.


2 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
like image 76
Namnodorel Avatar answered Oct 27 '22 00:10

Namnodorel


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

like image 36
andylamax Avatar answered Oct 27 '22 00:10

andylamax