Skip to content

Instantly share code, notes, and snippets.

@maca134
Last active May 20, 2025 18:17
Show Gist options
  • Save maca134/cd9fd5fdddddcaca13b05fa08681f196 to your computer and use it in GitHub Desktop.
Save maca134/cd9fd5fdddddcaca13b05fa08681f196 to your computer and use it in GitHub Desktop.
Bun + Hono Dynamic HTML Bundler Example
import { Hono } from "hono";
export async function bundler(
entrypoint: Bun.HTMLBundle,
config?: Bun.BuildConfig,
) {
let router = new Hono();
const build = await Bun.build({
...config,
entrypoints: [entrypoint.index],
outdir: undefined,
});
if (!build.success) {
build.logs.forEach((log) => console.log(log));
throw new Error("Build failed");
}
for (const file of build.outputs) {
const path = file.path.slice(2);
const handler = () =>
new Response(file.stream(), {
headers: {
"Content-Type": file.type,
"Cache-Control": "no-store",
},
status: 200,
});
if (path === "index.html" || path === "index.htm") {
router.get("/", handler);
}
router.get(path, handler);
}
return router;
}
@maca134
Copy link
Author

maca134 commented May 20, 2025

Bun + Hono Dynamic HTML Bundler Example

This code sets up a minimal web server using Hono and Bun to serve a web application with dynamic, in-memory asset bundling.

How it works

  • Imports an HTML entrypoint from a shared web package, using Bun.HTMLBundle.
  • Initializes a Hono server instance.
  • Uses a custom bundler function to bundle the HTML entrypoint and its dependencies at runtime.
  • Routes all requests to / through the dynamically bundled application.

Example (index.ts)

import index from "@repo/web/index.html";
import { Hono } from "hono";

import { bundler } from "./bundler";

const app = new Hono();

app.route("/", await bundler(index));

app.get("/api/hello", (c) => {
  return c.json({ message: "Hello from the API!" });
});

export default app;

Features

  • No pre-bundling required: Assets are bundled and served on-the-fly.
  • Automatic routing: All bundled files are accessible via their paths.
  • Development-friendly: Ideal for rapid prototyping or development environments.

Note: This setup is best for development or prototyping. For production, pre-bundle your assets for better performance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment