-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve.mjs
66 lines (57 loc) · 2.1 KB
/
serve.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
58
59
60
61
62
63
64
65
66
// serve.js
//const esbuild = require("esbuild");
import * as esbuild from 'esbuild'
import * as http from 'http'
const serve = async (servedir, listen) => {
let ctx = await esbuild.context({
entryPoints: ["./src/index.js"],
outfile: "./public/assets/app.js",
bundle: true,
loader: {
".js": "jsx",
},
plugins: [],
define: {
"process.env.PUBLIC_URL": JSON.stringify(process.env.PUBLIC_URL),}
})
// Start esbuild's local web server. Random port will be chosen by esbuild.
// edited to start actually randomly
const { host, port } = await ctx.serve({
servedir: "public",
port: Math.floor(Math.random() * (6000 - 5000 + 1) + 5000) ,
onRequest: (message) => {console.log(message.method, message.status, message.path)},
}, {});
//console.log(port)
// Create a second (proxy) server that will forward requests to esbuild.
const proxy = http.createServer((req, res) => {
// forwardRequest forwards an http request through to esbuid.
const forwardRequest = (path) => {
const options = {
hostname: host,
port,
path,
method: req.method,
headers: req.headers,
};
const proxyReq = http.request(options, (proxyRes) => {
if (proxyRes.statusCode === 404) {
// If esbuild 404s the request, assume it's a route needing to
// be handled by the JS bundle, so forward a second attempt to `/`.
return forwardRequest("/");
}
// Otherwise esbuild handled it like a champ, so proxy the response back.
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});
req.pipe(proxyReq, { end: true });
};
// When we're called pass the request right through to esbuild.
forwardRequest(req.url);
});
// Start our proxy server at the specified `listen` port.
proxy.listen(listen);
};
// Serves all content from ./dist on :1234.
// If esbuild 404s the request, the request is attempted again
// from `/` assuming that it's an SPA route needing to be handled by the root bundle.
serve("public", 3000);