Home

Awesome

bun-html-live-reload

HTML live reload for Bun

Getting Started

bun add -d bun-html-live-reload
// example.ts
import { withHtmlLiveReload } from "bun-html-live-reload";

Bun.serve({
  fetch: withHtmlLiveReload(async (request) => {
    return new Response("<div>hello world</div>", {
      headers: { "Content-Type": "text/html" },
    });
  }),
});

Options

eventPath and scriptPath

You can specify URL paths used for server-sent events and live reloader script.

Bun.serve({
  fetch: withHtmlLiveReload(
    async (request) => {
      /* ... */
    },
    {
      // SSE Path
      // default: "/__dev__/reload"
      eventPath: "/__reload",

      // Live reload script path
      // default: "/__dev__/reload.js"
      scriptPath: "/__reload.js",
    },
  ),
});

Manually reload clients

You can manually reload clients (refresh tabs) by calling reloadClients function.

import { withHtmlLiveReload, reloadClients } from "bun-html-live-reload";

Bun.serve({
  fetch: withHtmlLiveReload(async (request) => {
    /* ... */
  }),
});

// reload clients every second
setInterval(() => {
  reloadClients();
}, 1000);

Changes from v0.1

Migration from v0.1

v0.1

import { withHtmlLiveReload } from "bun-html-live-reload";
import { $ } from "bun";

export default Bun.serve(
  withHtmlLiveReload(
    {
      fetch: (request) => {
        /* ... */
      },
    },
    {
      watchPath: path.resolve(import.meta.dir, "src"),
      buildConfig: {
        entrypoints: ["./src/index.tsx"],
        outdir: "./build",
      },
      onChange: async () => {
        await $`rm -r ./dist`;
      },
    },
  ),
);

v1.0

import { withHtmlLiveReload, reloadClients } from "bun-html-live-reload";
import { FSWatcher, watch } from "fs";
import { $ } from "bun";

const buildConfig = {
  entrypoints: ["./src/index.tsx"],
  outdir: "./build",
};

Bun.build(buildConfig);

watch(path.resolve(import.meta.url, "src")).on("change", async () => {
  await $`rm -r ./dist`;
  await Bun.build(buildConfig);
  reloadClients();
});

Bun.serve({
  fetch: withHtmlLiveReload(async (request) => {
    /* ... */
  }),
});