Skip to content

Instantly share code, notes, and snippets.

@Rattlyy
Last active April 25, 2024 18:19
Show Gist options
  • Save Rattlyy/bfb751043b200138b43b200edc720a05 to your computer and use it in GitHub Desktop.
Save Rattlyy/bfb751043b200138b43b200edc720a05 to your computer and use it in GitHub Desktop.
Simple HMR with Jte and Ktor
new EventSource("/hmr").onmessage = (event) => location.reload()
import gg.jte.ContentType
import gg.jte.TemplateEngine
import gg.jte.resolve.DirectoryCodeResolver
import gg.jte.watcher.DirectoryWatcher
import io.ktor.server.application.*
import io.ktor.server.jte.*
import io.ktor.server.routing.*
import io.ktor.server.sse.*
import java.nio.file.Path
fun Application.configureJte() {
val resolver = DirectoryCodeResolver(Path.of("src/main/jte"))
val templateEngine = TemplateEngine.create(resolver, ContentType.Html)
val watcher = DirectoryWatcher(templateEngine, resolver)
var shouldReload = false
watcher.start {
shouldReload = true
}
install(Jte) {
this.templateEngine = templateEngine
}
routing {
sse("/hmr") {
while (!shouldReload) {
// wait...
}
send("hmr", "message")
shouldReload = false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment