Using external javascript library


#1

Hello. I’m trying to use the chart.js library in my kotlin project but can’t get it to work.

I downloaded the index.d.ts from https://www.npmjs.com/package/@types/chart.js
and used ts2kt to generate kotlin definitions. I then included this file in my project and the dependency in the build.gradle (i’m using the kotlin frontend plugin)

kotlinFrontEnd {
    npm {
          ...
          dependency("@types/chart.js", "2.7.25")
          ...
    }
}

However, when i load my webpage, i get the following error in the console:

"Uncaught ReferenceError: Chart is not defined"

I tried to fix this by adding the line (and variations like “Chart”, “@types/chart.js”):

@file:JsModule("chart.js")

to the ts2kt generated file, but then my build fails with the message:

"Module not found: Error: Can't resolve 'chart.js' in '/home/myproject/build/js'"

How can i fix this?


#2

I’m not sure what solution is but I’m interested to see a good example of someone using Chart.js with Kotlin.


#3

Looks like you have not declared actual chart.js only typescript type definitions.
Try adding dependency(“chart.js”)


#4

Thank you @Konstantin-Khvan, it worked! (the JsModule annotation was also needed)