Kotlin / kotlin-frontend-plugin

Gradle Kotlin (http://kotlinlang.org) plugin for frontend development
Apache License 2.0
561 stars 69 forks source link

Import a js module for its side effects only #149

Closed dvekeman closed 5 years ago

dvekeman commented 5 years ago

Is there a way to import / define / annotate a node module for its side effects only?

For example: Vaadin Elements (source: https://vaadin.com/tutorials/using-web-components)

Install the components

import '@vaadin/vaadin-button';

In JS this will load the module and some side effects will be applied to the HTML page (custom styles, dom-module nodes, ...).

In Kotlin Js, importing a module which is not explicitly used has no effect.

@JsModule("@vaadin/vaadin-button")
@JsNonModule
external val vbutton: HTMLElement? = definedExternally

fun main() {
    //console.log(vbutton?.toString())
    val mainDiv = document.getElementById("main")
    mainDiv?.append {
        vaadin_button {
            attributes["id"] = "hello"
            +"Hello"
        }
    }
}

Everything works fine when I uncomment the console.log line but I was wondering if there was a better way.

An example project can be found here: https://github.com/dvekeman/vaadin-elements-kotlin/tree/sideeffects (sideeffects branch)

andylamax commented 5 years ago

I think for that to happen, you should use require instead of just defining an external module

    require("@vaadin/vaadin-button")
dvekeman commented 5 years ago

Thanks for the feedback. That seems to work!

external fun require(module:String):dynamic

fun main() {
    require("@vaadin/vaadin-button")
    require("@vaadin/vaadin-text-field")
...
}