Skip to content

Commit

Permalink
Merge pull request #408 from moonbitlang/zhiyuan/live-load
Browse files Browse the repository at this point in the history
enable live reload
  • Loading branch information
bzy-debug authored Jan 8, 2025
2 parents 5624669 + 591e8a1 commit a5fc73e
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
47 changes: 45 additions & 2 deletions moonbit-tour/build/build.mts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as chokidar from "chokidar";
import * as esbuild from "esbuild";
import { tailwindPlugin } from "esbuild-plugin-tailwindcss";
import * as fs from "fs/promises";
import * as http from "http";
import * as path from "path";
import * as page from "./page";

Expand All @@ -24,6 +25,8 @@ const plugin = (): esbuild.Plugin => {
build.onEnd(async () => {
console.log("end build");

await fs.cp("./public", "./dist", { recursive: true });

const names = ["lsp-server.js", "moonc-worker.js", "onig.wasm"];
await Promise.all(
names.map((name) => {
Expand Down Expand Up @@ -67,7 +70,13 @@ const ctx = await esbuild.context({
".ttf": "file",
".woff2": "file",
},
logLevel: "info",
drop: isDev ? [] : ["console", "debugger"],
dropLabels: isDev ? [] : ["DEV"],
banner: isDev
? {
js: '(() => new EventSource("/esbuild").onmessage = () => location.reload())();',
}
: undefined,
plugins: [tailwindPlugin(), plugin()],
});

Expand All @@ -77,10 +86,42 @@ if (isBuild) {
process.exit(0);
}

const clients: http.ServerResponse[] = [];

if (isDev) {
await ctx.serve({
const { host, port } = await ctx.serve({
servedir: "dist",
});
const server = http.createServer((req, res) => {
if (req.url === "/esbuild") {
clients.push(
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
}),
);
return;
}
req.pipe(
http.request(
{
host,
port,
path: req.url,
method: req.method,
headers: req.headers,
},
(prxRes) => {
res.writeHead(prxRes.statusCode || 0, prxRes.headers);
prxRes.pipe(res, { end: true });
},
),
{ end: true },
);
});
server.listen(3000);
console.log(`Local: http://localhost:3000`);
}

if (isWatch) {
Expand All @@ -91,5 +132,7 @@ if (isWatch) {
.on("all", async (e, path) => {
console.log(`[watch] ${e} ${path}`);
await ctx.rebuild();
clients.forEach((res) => res.write("data: update\n\n"));
clients.length = 0;
});
}
2 changes: 1 addition & 1 deletion moonbit-tour/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"type": "module",
"scripts": {
"dev": "DEV=true tsx ./build/build.mts --watch",
"build": "tsc && tsx ./build/build.mts --build",
"build": "tsc && DEV=false tsx ./build/build.mts --build",
"preview": "serve dist",
"format": "prettier --write ."
},
Expand Down

0 comments on commit a5fc73e

Please sign in to comment.