diff --git a/moonbit-tour/build/build.mts b/moonbit-tour/build/build.mts index 7495e6c7..e5c23a74 100644 --- a/moonbit-tour/build/build.mts +++ b/moonbit-tour/build/build.mts @@ -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"; @@ -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) => { @@ -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()], }); @@ -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) { @@ -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; }); } diff --git a/moonbit-tour/package.json b/moonbit-tour/package.json index 44fb5048..b41be1b6 100644 --- a/moonbit-tour/package.json +++ b/moonbit-tour/package.json @@ -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 ." },