-
Notifications
You must be signed in to change notification settings - Fork 0
/
start.mjs
57 lines (49 loc) · 1.5 KB
/
start.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Based on https://github.com/evanw/esbuild/issues/1601#issuecomment-937961652
import { context } from "esbuild";
import { createServer, request } from "http";
const publicPort = 1274;
const define = {};
// FIXME: commented because in Windows is not supported
// for (const k in process.env) {
// define[`process.env.${k}`] = JSON.stringify(process.env[k]);
// }
const ctx = await context({
entryPoints: ["src/index.tsx"],
bundle: true,
minify: false,
sourcemap: true,
define,
outfile: "www/dist/index.js",
format: "esm",
});
const { host, port } = await ctx.serve({
servedir: "www",
});
const server = createServer((req, res) => {
const options = {
hostname: host,
port: port,
path: req.url,
method: req.method,
headers: req.headers,
};
const proxyReq = request(options, (proxyRes) => {
const date = new Date();
console.log(`${date.toISOString()} - ${req.method} to ${req.url}`);
if (proxyRes.statusCode === 404) {
const redirectReq = request({ ...options, path: "/" }, (proxyRes) => {
console.log(` ↳ redirected to /`);
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});
redirectReq.end();
} else {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
}
});
req.pipe(proxyReq, { end: true });
});
server.listen(publicPort);
console.log(`Listening at http://localhost:${publicPort}/`);
console.log("Watching for changes...");