Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Serve A JavaScript ES Module With axum

ES Modules must be served with a Content-Type of "text/javascript". This is how I'm doing that with axum

Code

use axum::{
    body::{Bytes, Full},
    response::Html,
    response::Response,
    routing::get,
    Router,
};
use std::fs;

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(home_page))
        .route("/script.js", get(response));
    axum::Server::bind(&"0.0.0.0:5550".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

async fn home_page() -> Html<String> {
    Html(fs::read_to_string("src/page.html").unwrap())
}

async fn response() -> Response<Full<Bytes>> {
    Response::builder()
        .header("Content-Type", "text/javascript")
        .body(Full::from(fs::read_to_string("src/script.js").unwrap()))
        .unwrap()
}

Code

function hw () {
  console.log("Hello, ES Module")
}

export { hw }

Code

<!DOCTYPE html>
<html>

<head>
  <style>
    body: {
      background-color: black;
      color: #876876;
    }
  </style>
  <script type="module">
    import {hw} from "./script.js"
    hw()
  </script>
</head>

<body>
  Hello, axum
</body>

</html>