forked from nuxt-contrib/vue3-ssr-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.mjs
50 lines (40 loc) · 1.22 KB
/
server.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
import fs from 'fs'
import path from 'path'
import express from 'express'
import { createServer } from 'vite'
const resolve = (p) => path.resolve(p)
const app = express()
const vite = await createServer({
root: resolve('.'),
logLevel: 'info',
server: {
middlewareMode: true,
appType: 'custom',
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(resolve('index.html'), 'utf-8'));
const { render } = await vite.ssrLoadModule('/src/entry-server.ts');
const renderRes = await render(url);
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');
})