-
Notifications
You must be signed in to change notification settings - Fork 8
/
server-dev.js
46 lines (35 loc) · 1.11 KB
/
server-dev.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
/* eslint-disable @typescript-eslint/no-var-requires */
const fs = require('fs')
const path = require('path')
const Koa = require('koa')
const koaConnect = require('koa-connect')
const vite = require('vite')
const root = process.cwd()
const resolve = (p) => path.resolve(__dirname, p)
;(async () => {
const app = new Koa()
const viteServer = await vite.createServer({
root,
logLevel: 'error',
server: {
middlewareMode: true,
},
})
app.use(koaConnect(viteServer.middlewares))
app.use(async ctx => {
try {
let template = fs.readFileSync(resolve('index.html'), 'utf-8')
template = await viteServer.transformIndexHtml(ctx.path, template)
const { render } = await viteServer.ssrLoadModule('/src/entry-server.ts')
const [appHtml] = await render(ctx, {})
const html = template.replace('<!--app-html-->', appHtml)
ctx.type = 'text/html'
ctx.body = html
} catch (e) {
viteServer && viteServer.ssrFixStacktrace(e)
console.log(e.stack)
ctx.throw(500, e.stack)
}
})
app.listen(3000, () => console.log('http://localhost:3000'))
})()