-
Notifications
You must be signed in to change notification settings - Fork 1
/
dev.server.mjs
74 lines (68 loc) · 2.17 KB
/
dev.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'url'
import express from 'express'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const resolve = p => path.resolve(__dirname, p);
const head = JSON.parse(fs.readFileSync(resolve('head.json'),'utf8'));
const PORT = 8010;
function renderHead(url, head) {
const page = url.replace('/', '');
const { title,keywords,description } = head[page];
return `
<title>${title}</title>
<meta name="description" content="${description}">
<meta name="keywords" content="${keywords}">
`
}
export async function createServer(hmrPort) {
const app = express()
let vite = await (
await import('vite')
).createServer({
base: '/ssr/',
root:process.cwd(),
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
},
hmr: {
port: hmrPort
}
},
appType: 'custom'
})
// use vite's connect instance as middleware
app.use(vite.middlewares)
let render = (await vite.ssrLoadModule('/src/entry-server.js')).render
app.use('*', async (req, res) => {
try {
const url = req.originalUrl.replace('/ssr/', '/')
let template = fs.readFileSync(resolve('index.html'), 'utf-8')
template = await vite.transformIndexHtml(url, template)
const [appHtml, preloadLinks,store] = await render(url, {})
const headStr = renderHead(url, head);
let html = template
.replace(`<!--preload-head-->`, headStr)
.replace(`<!--preload-links-->`, preloadLinks)
.replace(`<!--app-html-->`, appHtml)
// 数据传输
html += `<script>window.cache = ${JSON.stringify(store.state.value.cache)}</script>`
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
} catch (e) {
vite && vite.ssrFixStacktrace(e)
console.log(e)
res.status(500).end(e.stack)
}
})
return { app, vite }
}
createServer().then(({ app }) =>
app.listen(PORT, () => {
console.log('http://localhost:'+PORT)
})
)