https://kotlinlang.org logo
#javascript
Title
# javascript
r

Reuben Firmin

11/30/2023, 6:16 PM
How do I map libraries which need require? https://htmx.org/docs/#webpack as an example
I attempted via:
Copy code
@file:JsModule("<http://htmx.org|htmx.org>")
@file:JsNonModule
package ah.libs

// see <https://htmx.org/docs/#webpack> (i'm not bothering with the window injection yet)
@JsName("htmx")
external object HTMX {
    // see <https://htmx.org/docs/#init_3rd_party_with_events>
    fun onLoad(initializer: (content: Any) -> Unit)
}
the first part works (it imports, initializes, etc)
but the "htmx" object isn't available - probably because I'm not setting it up in the way they describe
a

andylamax

11/30/2023, 9:21 PM
if you are adding htmx as a script tag, just define externals without @JsModule
something like
Copy code
external fun require(mod: String): dynamic
then in your main function
Copy code
window.asDynamic().htmx = require("<http://htmx.org|htmx.org>")
should do the trick
r

Reuben Firmin

11/30/2023, 10:29 PM
thanks, that did the job
👍 1
a

Artem Kobzar

12/01/2023, 9:20 AM
Better solution, will be to put the JsModule (and JsNonModule) annotation directly on the object. It will not require the hack with the hack with 'require' function
a

andylamax

12/01/2023, 9:33 AM
I agree. So something like
Copy code
@file:JsModule("<http://htmx.org|htmx.org>")
@file:JsNonModule
package ah.libs

// see <https://htmx.org/docs/#webpack> (i'm not bothering with the window injection yet)
@JsName("htmx")
external object HTMX {
    // see <https://htmx.org/docs/#init_3rd_party_with_events>
    fun onLoad(initializer: (content: Any) -> Unit)
}
then in main function
Copy code
window.asDynamic().htmx = HTMX
a

Artem Kobzar

12/01/2023, 12:14 PM
More like this:
Copy code
package ah.libs

// see <https://htmx.org/docs/#webpack> (i'm not bothering with the window injection yet)
@JsModule("<http://htmx.org|htmx.org>")
@JsNonModule
external object HTMX {
    // see <https://htmx.org/docs/#init_3rd_party_with_events>
    fun onLoad(initializer: (content: Any) -> Unit)
}
a

andylamax

12/01/2023, 12:38 PM
isn't htmx implementations dependent upon htmx being defined on the windows object yet
a

Artem Kobzar

12/01/2023, 1:32 PM
Yeap it could be added in the same way after:
Copy code
window.asDynamic().htmx = HTMX