Skip to content

Instantly share code, notes, and snippets.

@kitlangton

kitlangton/HMR.scala

Created Jun 11, 2021
Embed
What would you like to do?
Example of basic HMR with Scala.js & Laminar
object Main {
val css: Css.type = Css
println(s"PRODUCTION MODE: ${scala.scalajs.LinkingInfo.productionMode}")
def main(args: Array[String]): Unit =
waitForLoad {
val appContainer = dom.document.querySelector("#app")
appContainer.innerHTML = ""
unmount()
println("RENDER")
val rootNode = render(appContainer, Frontend.view)
storeUnmount(rootNode)
}
def waitForLoad(f: => Any): Unit =
if (dom.window.asInstanceOf[js.Dynamic].documentLoaded == null)
documentEvents.onDomContentLoaded.foreach { _ =>
dom.window.asInstanceOf[js.Dynamic].documentLoaded = true
f
}(unsafeWindowOwner)
else
f
def unmount(): Unit =
if (scala.scalajs.LinkingInfo.developmentMode) {
Option(dom.window.asInstanceOf[js.Dynamic].__laminar_root_unmount)
.collect {
case x if !js.isUndefined(x) =>
println("UNMOUNT")
x.asInstanceOf[js.Function0[Unit]]
}
.foreach { _.apply() }
}
def storeUnmount(rootNode: RootNode): Unit = {
val unmountFunction: js.Function0[Any] = () => {
rootNode.unmount()
}
println("STORE UNMOUNT")
dom.window.asInstanceOf[js.Dynamic].__laminar_root_unmount = unmountFunction
}
if (`import`.meta.hot != null) {
println("HOT RELOADING ENABLED")
`import`.meta.hot.accept { (_: Any) => }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment