A bunch of interesting K/JS fixes landed in 2.0.0-...
# javascript
e
A bunch of interesting K/JS fixes landed in 2.0.0-Beta2! https://github.com/JetBrains/kotlin/releases/tag/v2.0.0-Beta2 If I understood correctly, https://youtrack.jetbrains.com/issue/KT-61523 allows us to have multiple
main
functions, on each file inside the same Gradle module. This means we can develop browser extensions without having to split each extension part on its own module.
a
Hey, no. Unfortunately, it's the opposite. Before this fix, we had a problem that for each file with its main function, we call it. This behavior breaks Kotlin semantic, so I implemented the same algorithm in the per-file that we use right now in the per-module.
e
Ah damn, thanks for the correction, so there won't ever be a way to have a per-file main?
a
I think so. It will break the current semantic of the main function.
e
Could a compiler plugin help? Just wondering if we can "hack" it
a
I believe that in this case you could try to use
EagerInitialization
. It will bring effect inside the file, and in per-file I use
import "something"
to add it into the "module" file.
It could help with your use-case
e
By module file you mean the single entry point? I guess if I were to be in a browser extension context that entry point would be discarded from the final bundle.
Example, you'd have a
background.kt
and a
popup.kt
, living in the same module. Each will have a function that must be called when the file is loaded
a
Yes, I believe it could be solved with the current implementation of the EagerInitialization in per-file
gratitude thank you 1
e
But I'd need to place the annotation on a property. Maybe I can just return a
Unit
from the function
Looks like it might work tho, in theory. Another case for not removing that deprecated annotation.
👍 1
For the following code:
Copy code
@file:JsFileName("background")

@Suppress("DEPRECATION")
@OptIn(ExperimentalStdlibApi::class)
@EagerInitialization
val init = background()

fun background() {
    println("eager print line")
}
This is outputted:
Copy code
var init;
function background() {
  println('eager print line');
}
function init$init$() {
  background();
  return Unit_instance;
}
//region block: init
init = init$init$();
//endregion
So I wonder if this is still valid: https://youtrack.jetbrains.com/issue/KT-51626/
Technical question: why is the
background
call wrapped in a
init$init$
function?
@turansky this looks like a good candidate for a plugin, what do you think? One could annotate a function and the plugin could create an associated private property annotated with
EagerInitialization
. Not sure if it's feasible
t
Copy code
val init = run {
   // your sideeffect
}
In any case initial problem is more important
e
Could work, a bit strange looking tho if someone else that doesn't know why it's done like that looks at it 😂