-
Notifications
You must be signed in to change notification settings - Fork 6
/
server.js
51 lines (40 loc) · 1.21 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
import fs from 'node:fs'
import path from 'node:path'
import express from 'express'
import { createServer } from 'vite'
const app = express()
const vite = await createServer({
root: path.resolve('.'),
logLevel: 'info',
appType: 'custom',
server: {
middlewareMode: true,
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) => {
try {
const url = req.originalUrl || req.url;
const template = await vite.transformIndexHtml(url, fs.readFileSync(path.resolve('index.html'), 'utf-8'));
const { render } = await vite.ssrLoadModule('/src/entry-server.ts');
const renderRes = await render(url);
console.log()
const html = template
.replace(`<!--app-html-->`, renderRes.html);
res.status(200).set({ 'Content-Type': 'text/html' }).end(html);
} catch (e) {
vite && vite.ssrFixStacktrace(e);
console.error(e.stack);
res.status(500).end(e.stack);
}
});
app.listen(3000, () => {
console.log('http://localhost:3000');
})