https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
javascript
  • k

    KV

    05/09/2022, 5:22 PM
    Can someone please suggest me the regex for email address according to below image?
    j
    v
    • 3
    • 9
  • d

    David Corrado

    05/09/2022, 11:51 PM
    How do you get ktor suspend function working inside of application that uses JSExport. I have an example JsExport repo here https://github.com/DavidCorrado/KMPWithWeb/blob/main/shared/src/jsMain/kotlin/com/example/kmpwithweb/PokemonList2ViewModel.kt
    g
    h
    d
    • 4
    • 27
  • t

    tylerwilson

    05/11/2022, 2:51 AM
    Revisiting getting my multi-platform working with JS target again, and I am getting this after including Ktor JS:
    Couldn't find package "abort-controller@3.0.0" required by "ktor-ktor-client-core-js-ir@1.6.8" on the "npm" registry.
    Anybody know how to fix this? There are a number of other bits missing too (ws, webpack, @js-joda/core)
    b
    • 2
    • 9
  • m

    martmists

    05/11/2022, 2:29 PM
    How do I set the filename to
    index.js
    in a multiplatform project? I tried it like this but it still uses the project name instead:
    js("frontend", IR) {
            binaries.executable()
            browser {
                commonWebpackConfig {
                    cssSupport.enabled = true
                    output?.library = "index"  // tell it to generate as index.js
                }
            }
        }
    t
    • 2
    • 1
  • d

    dazza5000

    05/11/2022, 3:15 PM
    anyone know why a property that we are instantiating in a ViewModel class is undefined when we actually try to use it - this property is undefined when we try to use it https://github.com/DavidCorrado/KMPWithWeb/blob/7560f6a9c58dd2a200227764ca6427eee9[…]c/jsMain/kotlin/com/example/kmpwithweb/PokemonList2ViewModel.kt
    a
    • 2
    • 5
  • d

    dazza5000

    05/11/2022, 4:50 PM
    Does anyone have a good reference project for using a shared/common viewmodel in kotlin/js and calling the viewmodel functions from pure html/js/reactjs (not implementing the web in kotlin/js or a kotlin dsl/wrapper)
    d
    x
    • 3
    • 4
  • p

    peekandpoke

    05/12/2022, 11:54 AM
    Hi there! I am getting an Internal Compiler Error, on Kotlin 1.6.21 trying to run javascript tests:
    > Task :core:compileTestDevelopmentExecutableKotlinJs FAILED
    e: java.lang.NullPointerException
            at org.jetbrains.kotlin.ir.backend.js.ic.InvalidationKt.actualizeCacheForModule(invalidation.kt:444)
            at org.jetbrains.kotlin.cli.js.K2JsIrCompiler.doExecute(K2JsIrCompiler.kt:220)
            at org.jetbrains.kotlin.cli.js.K2JSCompiler.doExecute(K2JSCompiler.java:178)
            at org.jetbrains.kotlin.cli.js.K2JSCompiler.doExecute(K2JSCompiler.java:71)
            at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:91)
            at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:43)
            at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:93)
            at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:1623)
            at sun.reflect.GeneratedMethodAccessor82.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
            at sun.rmi.transport.Transport$1.run(Transport.java:200)
            at sun.rmi.transport.Transport$1.run(Transport.java:197)
            at java.security.AccessController.doPrivileged(Native Method)
            at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
            at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
            at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
            at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
            at java.security.AccessController.doPrivileged(Native Method)
            at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
            at java.lang.Thread.run(Thread.java:748)
    It worked and suddenly stopped working. We are also not doing anything fancy here. Just a normal gradle.build configuration. I see that the NPE is thrown here in `invalidation.kt:444`:
    c
    • 2
    • 13
  • d

    David Smith

    05/12/2022, 2:39 PM
    I’m trying to compile to js on a multi platform project on a linux arm64 machine but gradle is downloading an x86 nodejs binary, any idea how I can tell it what platform I’m on?
    • 1
    • 1
  • d

    David Smith

    05/12/2022, 3:44 PM
    Ok, with a multiplatform project I’m getting the following error:
    Execution failed for task ':admin-app:kaptGenerateStubsKotlin'.
    > Error while evaluating property 'filteredArgumentsMap' of task ':admin-app:kaptGenerateStubsKotlin'
       > Could not resolve all files for configuration ':admin-app:kotlinCompilerPluginClasspathMain'.
          > Could not find org.jetbrains.kotlin:kotlin-allopen:1.6.21.
            Required by:
                project :admin-app
          > Could not find org.jetbrains.kotlin:kotlin-scripting-compiler-embeddable:1.6.21.
            Required by:
                project :admin-app
          > Could not find org.jetbrains.kotlin:kotlin-annotation-processing-gradle:1.6.21.
            Required by:
                project :admin-app
    • 1
    • 3
  • v

    Vitaly Khvostov

    05/13/2022, 9:30 AM
    Hi! Is the library
    kotlin-mui-icons
    broken or it's only in my environment? Firstly it broke when I bumped version of my project to 1.0.0-pre.336; then, I tried to run both a test project and Kotlin Mui Showcase (https://github.com/karakum-team/kotlin-mui-showcase) which use MUI icons, and they show an error like in the attachments.
    t
    • 2
    • 7
  • d

    David Smith

    05/13/2022, 2:37 PM
    I’m trying to output a typescript definition file using MPP and the IR compiler, I have a simple data class in
    commonMain
    @JsExport
    data class Hello(val something: String)
    and in my build.gradle.kts I have
    js(IR) {
            browser {
                binaries.executable()
            }
        }
    when I try to do
    gradle build
    or I can see that something is compiled however there is no
    build/js
    directory and I have no idea where this has been created
    d
    h
    • 3
    • 9
  • s

    Sergei Grishchenko

    05/13/2022, 7:10 PM
    Small survey from
    kotlin-wrappers
    What kind of Kotlin DSL for React Context Provider do you like? React with 👈 if you like classic syntax
    CustomContext.Provider(value) {
      Child {}
    }
    React with 👉 if you like shortcut syntax
    CustomContext(value) {
      Child {}
    }
    Thank you for feedback
    👈 3
    👉 2
    t
    • 2
    • 3
  • g

    Gopal S Akshintala

    05/15/2022, 11:38 AM
    Can someone please point me to any working examples that demonstrate Use JavaScript code from Kotlin. I am interested more on the code that interacts with external NPM packages, similar to the one in this blog post: JS in Kotlin/JS - DEV Community :woman::computer::man::computer: Most of the repos I see only has examples with React and I am not looking for those. Thanks.
    r
    j
    v
    • 4
    • 3
  • r

    Ran

    05/18/2022, 8:16 AM
    I want to use bignumber.js in kotlin. Import:
    val jsMain by getting {
                dependencies {
                    implementation(npm("bignumber.js", "9.0.2"))
                }
            }
    Declaration:
    @JsModule("bignumber.js")
    @JsNonModule
    external class BigNumber(raw: String) {
    
        companion object {
            var ROUND_UP: Number /* 0 */
            var ROUND_DOWN: Number /* 1 */
            var ROUND_CEIL: Number /* 2 */
            var ROUND_FLOOR: Number /* 3 */
            var ROUND_HALF_UP: Number /* 4 */
            var ROUND_HALF_DOWN: Number /* 5 */
            var ROUND_HALF_EVEN: Number /* 6 */
            var ROUND_HALF_CEIL: Number /* 7 */
            var ROUND_HALF_FLOOR: Number /* 8 */
    
            fun config(): Config
            fun set(obj: Config): Config
            fun clone(obj: Config = definedExternally): Any
        }
    
        interface Config {
            var DECIMAL_PLACES: Number?
                get() = definedExternally
                set(value) = definedExternally
            var ROUNDING_MODE: Number? /* 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 */
                get() = definedExternally
                set(value) = definedExternally
            var EXPONENTIAL_AT: dynamic /* Number? | JsTuple<Number, Number> */
                get() = definedExternally
                set(value) = definedExternally
            var RANGE: dynamic /* Number? | JsTuple<Number, Number> */
                get() = definedExternally
                set(value) = definedExternally
            var CRYPTO: Boolean?
                get() = definedExternally
                set(value) = definedExternally
            var MODULO_MODE: Number? /* 0 | 1 | 3 | 6 | 9 */
                get() = definedExternally
                set(value) = definedExternally
            var POW_PRECISION: Number?
                get() = definedExternally
                set(value) = definedExternally
            var FORMAT: Format?
                get() = definedExternally
                set(value) = definedExternally
            var ALPHABET: String?
                get() = definedExternally
                set(value) = definedExternally
        }
    
        interface Format {
            var prefix: String?
                get() = definedExternally
                set(value) = definedExternally
            var decimalSeparator: String?
                get() = definedExternally
                set(value) = definedExternally
            var groupSeparator: String?
                get() = definedExternally
                set(value) = definedExternally
            var groupSize: Number?
                get() = definedExternally
                set(value) = definedExternally
            var secondaryGroupSize: Number?
                get() = definedExternally
                set(value) = definedExternally
            var fractionGroupSeparator: String?
                get() = definedExternally
                set(value) = definedExternally
            var fractionGroupSize: Number?
                get() = definedExternally
                set(value) = definedExternally
            var suffix: String?
                get() = definedExternally
                set(value) = definedExternally
        }
    
        fun plus(number: BigNumber): BigNumber
        fun minus(number: BigNumber): BigNumber
        fun multipliedBy(number: BigNumber): BigNumber
        fun dividedBy(number: BigNumber): BigNumber
        fun modulo(number: BigNumber): BigNumber
        fun comparedTo(number: BigNumber): Number?
        fun toString(base: Int): String
    }
    Other methods work well except
    set
    and
    clone
    .
    @Test
        fun testConfig() {
            println(BigNumber.config().DECIMAL_PLACES)
            BigNumber.set(object : BigNumber.Config {
                override var DECIMAL_PLACES: Number? = 3
            })
            println(BigNumber.config().DECIMAL_PLACES)
        }
    the
    set
    method has no effect. The output is like the following:
    > Task :jsBrowserTest
    [log] 20
    [log] 20
    Is there anyone can tell me why the
    set
    method doesn't work and how can I use
    clone
    method?
    b
    • 2
    • 10
  • r

    Ran

    05/19/2022, 11:14 AM
    I encountered the following error:
    TypeError: Cannot read properties of undefined (reading 'plus_4zeyed$')
    I have the declaration in common:
    expect class BigDecimal(raw: String) {
        fun add(bigDecimal: BigDecimal): BigDecimal
        companion object {
            val ONE: BigDecimal
            val MAX: BigDecimal
            val MIN: BigDecimal
        }
    }
    
    internal val maxValue = ""
    internal val max = BigDecimal(maxValue)
    internal val minValue = ""
    internal val min = BigDecimal(minValue)
    In jsMain:
    @JsModule("bignumber.js")
    @JsNonModule
    external class BigNumber(raw: String) {
        fun plus(number: BigNumber): BigNumber
    }
    
    actual class BigDecimal actual constructor(raw: String) {
        private val delegate: BigNumber = BigNumber(raw)
    
        actual companion object {
            actual val ONE: BigDecimal = one
            actual val MAX: BigDecimal = max
            actual val MIN: BigDecimal = min
        }
    
        actual fun add(bigDecimal: BigDecimal): BigDecimal {
            return BigDecimal(delegate.plus(bigDecimal.delegate).toPlainString())
        }
    }
    I have following unit test:
    @Test
        fun testOverflow() {
            assertEquals(maxValue, (BigDecimal.MAX + BigDecimal.ONE).toPlainString())
        }
    I got the error I post when I run the unit test for js target. Is there anyone who can tell me what's wrong here?
    g
    • 2
    • 2
  • r

    Ran

    05/19/2022, 2:07 PM
    I wrote a multiplatform library and publish it to maven local. Then I use the library in another KMP project. Everything is ok except cannot run js unit tests in the KMP project. I add my library like the following:
    sourceSets {
        val commonMain by getting {
          dependencies {
            implementation("com.calculation.multiplatform:MultiplatformBigDecimal:1.0.0-beta6")
          }
        }
        val commonTest by getting {
          dependencies {
            implementation(kotlin("test"))
            implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2")
            implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.3.2")
          }
        }
      }
    The ios unit tests and JVM unit tests work well. But when I run js unit tests, I got the following error:
    Could not determine the dependencies of task ':jsTestPackageJson'.
    > Could not resolve all dependencies for configuration ':jsTestNpm'.
       > Could not resolve com.calculation.multiplatform:MultiplatformBigDecimal:1.0.0-beta6.
         Required by:
             project :
          > No matching variant of com.calculation.multiplatform:MultiplatformBigDecimal:1.0.0-beta6 was found. The consumer was configured to find a usage of 'kotlin-runtime' of a library, preferably optimized for non-jvm, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'js', attribute 'org.jetbrains.kotlin.js.compiler' with value 'ir' but:
    I cannot understand the message. Is there anyone who can tell me how can I solve this problem?
    g
    b
    • 3
    • 21
  • a

    Arjan van Wieringen

    05/20/2022, 8:51 AM
    Does anybody know a good way to handle runtime configuration? When working with serverside projects it is always easy, when developing, to start different Spring Boot configurations for instance by passing different Gradle parameters. How would I do something like that in Kotlin/Js?
    b
    • 2
    • 2
  • m

    Mihai Voicescu

    05/20/2022, 11:23 AM
    Hello, Our company started using Kotlin Multiplatform to share libraries between web, mobile and backend. The problem is at least in our experience the development of the actual UI layer on the web takes significantly longer in Kotlin than using TS (just looking at the time to compile it you can see a noticeable difference). Using Kotlin from TS is also a hassle due to suspend functions and conversions. With this in mind, we were thinking to take a similar approach to how mobile development works and separating the actual UI from the logic behind it (similar to MVVM architecture). This way we can write all the business logic in Kotlin and just expose the state and events to TS. 1. What do you think of this idea? 2. Did anybody attempt this? 3. What libraries do you recommend that can easily interact with both Kotlin and Typescript that can handle the state and UI events (eg RxJS)?
    👍 2
    b
    a
    j
    • 4
    • 6
  • r

    Ran

    05/23/2022, 3:18 AM
    I cannot run js unit tests through IDEA, but when I run the failed task on the terminal, it succeeded. Is there anyone who can tell me the reason?
    n
    v
    • 3
    • 3
  • m

    Mihai Voicescu

    05/23/2022, 1:20 PM
    Functions that return Promise seem to be converted to
    any
    in TS declarations in 1.6.20 Anybody know a fix for this? EG:
    @ExperimentalJsExport
    @JsExport
    fun test(): Promise<JSClient> {
        TODO()
    }
    
    @ExperimentalJsExport
    @JsExport
    fun useClient(): JSClient? {
    compiles to
    export function test(): any/* Promise<JSClient> */;
    export function useClient(): Nullable<JSClient>;
    👀 1
    c
    h
    m
    • 4
    • 3
  • a

    Alexander Sysoev

    05/23/2022, 3:33 PM
    Hello! How can i allow this in my project?
    Function types with receiver are prohibited in external declarations
    t
    m
    • 3
    • 8
  • a

    Alexander Sysoev

    05/23/2022, 5:20 PM
    In the new React api in FC components and html tags there is such type in context receiver (photo). Is there any way to make lambda with such receiver so i can write this code (or maybe there is an alternative):
    fun <P : Props> component(builder: {ChildrenBuilder & P & Props}.() -> Unit): FC<P> {
        return FC<P> {
            builder()
        }
    }
    t
    • 2
    • 7
  • j

    Jan

    05/23/2022, 6:16 PM
    What does that mean? (thread)
    h
    • 2
    • 2
  • j

    Joffrey

    05/24/2022, 6:31 PM
    I'm getting the following warning, and I think this is a bug of the Kotlin/JS tooling:
    There are multiple versions of "ktor-ktor-client-core-js-legacy" used in nodejs build: 1.6.8, 2.0.0. Only latest version will be used.
    I have 2 independent multiplatform submodules to support Ktor 1 and Ktor 2. They are never used together. When running js tests for the module using Ktor 1.6.8, I have runtime errors because it is in fact using Ktor 2 during tests. I noticed the
    build/js/packages/<module-name>/package.json
    doesn't contain any dependencies, and in fact all dependencies of all subprojects are mixed together in
    build/js/package.json
    as "workspaces", excluding collisions (so Ktor 1 is not there). Is this normal? Is there a way to change that?
    e
    • 2
    • 4
  • j

    Jonathan Ellis

    05/25/2022, 2:07 AM
    Should my expectation for dead code elimination be closer to, "it eliminates virtually all dead code" or "it's better than nothing but it doesn't scale well to large use cases?" I'm creating a project with the OPENRNDR framework as a dependency and the production js ends up at 700KB, which is about 10x what I was expecting.
    b
    • 2
    • 4
  • r

    Ran

    05/25/2022, 2:44 AM
    I have KMP library which jsMain depends on bignumber.js through npm:
    sourceSets {
            val jsMain by getting {
                dependencies {
                    implementation(npm("bignumber.js", "9.0.2"))
                }
            }
        }
    I published my KMP library to my private maven and use it in my another KMP project:
    sourceSets {
        val commonMain by getting {
          dependencies {
            implementation("com.calculation.multiplatform:MultiplatformBigDecimal:1.0.0")
          }
        }
      }
    Then I build js package in my KMP project use
    ./gradlew jsBrowserProductionWebpack
    command. The problem is that I cannot see peerDependencies on MultiplatformBigDecimal and bignumber.js
    b
    • 2
    • 15
  • m

    Marius Ailinca

    05/25/2022, 11:41 AM
    Hi! I am getting a Base64 encoded file (through API) from a ktor server from a compose for web application. The encoded string arrives well on the web but when I convert it to a Blob I guess something is not working since the file is not readable anymore (xlsx file). Here is the code that converts ByteArray to Blob
    fun bytesToFile(byteArray: ByteArray){
        val blob = Blob(byteArray.toTypedArray(), BlobPropertyBag("application/vnd.ms-excel"))
        val link = document.createElement("a") as HTMLAnchorElement
        link.href = URL.Companion.createObjectURL(blob)
        link.download = "test.xlsx"
        link.click()
        //document.removeChild(link)
    }
    Any idea what it might be wrong?
    b
    • 2
    • 4
  • p

    patrickdelconte

    05/25/2022, 12:31 PM
    The stdlib already exposes the webgl 1 api through the interface
    org.khronos.webgl.WebGLRenderingContext
    Are there any external types for the webgl2 api?
    t
    • 2
    • 1
  • m

    Mihovil Ilakovac

    05/25/2022, 3:08 PM
    Hey I have used the default template available in Android Studio for Kotlin Multiplatform Library and just added support for Javascript:
    js(IR) {
      browser()
      binaries.executable()
    }
    But the build fails immediately with the error:
    Caused by: org.gradle.api.internal.tasks.DefaultTaskContainer$DuplicateTaskException: Cannot add task 'clean' as a task with that name already exists.
    I’m not sure how to approach this, has anyone encountered a similar error? Gradle version: 7.3.3
    e
    • 2
    • 3
  • j

    Jonathan Ellis

    05/26/2022, 4:06 PM
    If I want to access an external javascript variable from my code, is
    js("foo") as Type
    the best option? What about going the other way around, do I need to generate
    js("foo = [js string representation]")
    ? This is easy for primitives but more tedious for other objects
    e
    b
    • 3
    • 19
Powered by Linen
Title
j

Jonathan Ellis

05/26/2022, 4:06 PM
If I want to access an external javascript variable from my code, is
js("foo") as Type
the best option? What about going the other way around, do I need to generate
js("foo = [js string representation]")
? This is easy for primitives but more tedious for other objects
e

ephemient

05/26/2022, 4:12 PM
external var foo: Type
j

Jonathan Ellis

05/26/2022, 4:19 PM
ah, thanks. wasn't sure from docs if that would work
I can't figure out how to get this to work with a map
<script>
        let foo = 0.0
        let bar = {}
    </script>
external var foo: Double
external var bar: MutableMap<String, Any>
foo = 1.0
bar["test"] = "a"
foo works as expected
bar says
Uncaught TypeError: tmp0_set_0.put_3mhbri_k$ is not a function
e

ephemient

05/26/2022, 5:50 PM
MutableMap
is a Kotlin type, but
{}
in JS is not
external val bar: dynamic
bar["test"] = "a"
j

Jonathan Ellis

05/26/2022, 5:53 PM
wow, black magic 🙂 that works
b

Big Chungus

05/26/2022, 6:07 PM
external val bar: Json It's safer and represents js object types
j

Jonathan Ellis

05/26/2022, 6:09 PM
perfect, thanks
e

ephemient

05/26/2022, 6:09 PM
dynamic
lets you write
bar.test = "a"
just like you can in JS, which you could consider a plus and/or a minus
j

Jonathan Ellis

05/26/2022, 6:10 PM
that makes sense
b

Big Chungus

05/26/2022, 6:27 PM
Dynamic type is basically an escape hatch to tell the compiler to completely drop the type safety. It's necessary to handle some janky js voodoo interop, but in general should be avoided as much as possible (otherwise you're better off to just coding in plain js)
Not sure if you've seen it yet, but I've written an article that covers most of what one needs to know when interoping with js https://dev.to/mpetuska/js-in-kotlinjs-c4g
j

Jonathan Ellis

05/26/2022, 6:32 PM
Reading now. Thanks!
View count: 15