kettle11 / devserver

A simple HTTPS server for local development. Implemented in Rust.
zlib License
95 stars 15 forks source link

Inject an auto-reload script into served pages #2

Closed Kixiron closed 4 years ago

Kixiron commented 4 years ago

livereload does this with this project, and it's amazing for developing when you don't have to constantly refresh the browser

kettle11 commented 4 years ago

Thanks for the feedback!

I agree auto-reload would be super useful. It's something I want myself.

Most approaches seem to be implemented by injecting code into HTML that listens for messages over a WebSocket.

The server would watch a folder for changes and send WebSocket messages to the page when something changes.

Devserver's only current dependency is native-tls, so it'd be a little sad to introduce additional dependencies, but I think the utility would be worth it.

An initial approach is to just refresh the page whenever a change is detected. A more fine-grained approach would be to allow for reloading CSS / HTML without reloading the entire page.

Kixiron commented 4 years ago

I do love that devserver has few dependencies, that's an amazing feature in of itself. With that in mind, file-watcher would probably be a good crate to look into, as it only has one dependency which itself has no dependencies.

As for fine grained, file-watcher allows explicitly adding files, so filtering for specific file types would be as simple as filtering files by their extensions before adding them to the watch list.

Alternatively, file-watcher isn't very complex and could be easily re-implemented, as it's little more than a loop on another thread that periodically checks the date the file was last modified. At only 155 lines, it's a pretty small thing to rewrite, and you'd probably gain performance gain from it if anything.

kettle11 commented 4 years ago

I started working on this on the following branch:

https://github.com/kettle11/devserver/tree/reload/

Right now it works: when anything in the hosted folder changes the page will be refreshed. But the code is a bit messy and could use some cleanup before it's merged to master and the crate updated.

I added the notify crate to handle monitoring folders. The sha-1 and base64 crates were added for a barebones WebSockets implementation.

With those three additions, clean build times have gone from ~11 seconds to ~21 seconds for me.

Given that the tool is primarily meant to be installed once via cargo, that seems like a reasonable cost for a very useful feature.

kettle11 commented 4 years ago

Ok, I merged the branch and updated thedevserver crate.

Pass the --reload flag to enable automatic page refresh when a file in the hosted folder changes.

It's pretty cool to be able to type and immediately see the changes show up. Obviously it's a feature other similar tools have had for a while, but still fun!

Thanks @Kixiron for the motivation to add this sooner rather than later!