/
server.js
98 lines (83 loc) · 2.36 KB
/
server.js
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// @ts-check
const fs = require('fs')
const path = require('path')
const express = require('express')
const isTest = process.env.NODE_ENV === 'test' || !!process.env.VITE_TEST_BUILD
const DYNAMIC_SCRIPTS = `
<script type="module">
const p = document.createElement('p');
p.innerHTML = '✅ Dynamically injected inline script';
document.body.appendChild(p);
</script>
<script type="module" src="/src/app.js"></script>
`
const DYNAMIC_STYLES = `
<style>
h1 {
background-color: blue;
}
</style>
`
async function createServer(
root = process.cwd(),
isProd = process.env.NODE_ENV === 'production'
) {
const resolve = (p) => path.resolve(__dirname, p)
const app = express()
/**
* @type {import('vite').ViteDevServer}
*/
let vite
vite = await require('vite').createServer({
root,
logLevel: isTest ? 'error' : 'info',
server: {
middlewareMode: 'ssr',
watch: {
// During tests we edit the files too fast and sometimes chokidar
// misses change events, so enforce polling for consistency
usePolling: true,
interval: 100
}
}
})
// use vite's connect instance as middleware
app.use(vite.middlewares)
app.use('*', async (req, res, next) => {
try {
let [url] = req.originalUrl.split('?')
if (url.endsWith('/')) url += 'index.html'
if (url.startsWith('/favicon.ico')) {
return res.status(404).end('404')
}
if (url.startsWith('/@id/__x00__')) {
return next()
}
const htmlLoc = resolve(`.${url}`)
let template = fs.readFileSync(htmlLoc, 'utf-8')
template = template.replace(
'</body>',
`${DYNAMIC_SCRIPTS}${DYNAMIC_STYLES}</body>`
)
// Force calling transformIndexHtml with url === '/', to simulate
// usage by ecosystem that was recommended in the SSR documentation
// as `const url = req.originalUrl`
const html = await vite.transformIndexHtml('/', template)
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
} catch (e) {
vite && vite.ssrFixStacktrace(e)
console.log(e.stack)
res.status(500).end(e.stack)
}
})
return { app, vite }
}
if (!isTest) {
createServer().then(({ app }) =>
app.listen(5173, () => {
console.log('http://localhost:5173')
})
)
}
// for test use
exports.createServer = createServer