generated from laaksonel/fullstack-reason-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.dev.mjs
79 lines (73 loc) · 2.39 KB
/
build.dev.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
67
68
69
70
71
72
73
74
75
76
77
78
79
import { build, serve } from 'esbuild';
import { createServer, request } from 'http';
import { htmlPlugin } from '@craftamap/esbuild-plugin-html';
const clients = [];
const entryFile = '_build/default/client/index.bs.js';
const buildDir = '_build/dev';
const htmlTempate = 'public/index.html';
build({
entryPoints: [entryFile],
bundle: true,
// These must be set for htmlPlugin
outdir: buildDir,
metafile: true,
// When the page first loads, this will open an event stream back to the client
banner: { js: ' (() => new EventSource("/esbuild").onmessage = () => location.reload())();' },
watch: {
onRebuild(error, result) {
// On every rebuild, send a update message via event stream
clients.forEach((res) => res.write('data: update\n\n'))
clients.length = 0
console.log(error ? error : '...')
},
},
plugins: [
htmlPlugin({
files: [
{
entryPoints: [entryFile],
filename: 'index.html',
htmlTemplate: htmlTempate
},
]
})
]
})
.catch(() => process.exit(1))
// Create a serve server to port 8000
serve({ servedir: buildDir }, {}).then(() => {
// Then create a new server to 3000
createServer((req, res) => {
const { url, method, headers } = req
// If esbuild, open a new event stream to the client
if (req.url === '/esbuild') {
return clients.push(
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
})
);
}
if (req.url === '/todos') {
req.pipe(
request({ hostname: '0.0.0.0', port: 3000, path: req.url, method, headers }, (prxRes) => {
res.writeHead(prxRes.statusCode, prxRes.headers)
prxRes.pipe(res, { end: true })
}),
{ end: true }
);
} else {
// Otherwise just pipe the request to the serve server
const path = ~url.split('/').pop().indexOf('.') ? url : `/index.html` //for PWA with router
console.log(`Path ${path}`);
req.pipe(
request({ hostname: '0.0.0.0', port: 8000, path, method, headers }, (prxRes) => {
res.writeHead(prxRes.statusCode, prxRes.headers)
prxRes.pipe(res, { end: true })
}),
{ end: true }
)
}
}).listen(3001)
})