-
Notifications
You must be signed in to change notification settings - Fork 8
/
server.js
70 lines (61 loc) · 1.99 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
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import express from 'express'
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
const resolve = (p) =>
path.resolve(path.dirname(fileURLToPath(import.meta.url)), p)
const createServer = async (isTest = false) => {
const isProd = process.env.NODE_ENV === 'production'
const app = express()
// configure vite service
let vite
if (isProd) {
app.use(require('compression')())
app.use(
require('serve-static')(resolve('./dist/client'), {
index: false
})
)
} else {
vite = await require('vite').createServer({
server: {
middlewareMode: true
},
appType: 'custom'
})
app.use(vite.middlewares)
}
// static resource mapping in prod env
const manifest = isProd
? fs.readFileSync(resolve('./dist/client/ssr-manifest.json'), 'utf-8')
: {}
app.use('*', async (req, res, next) => {
const url = req.originalUrl
try {
// get html template and rendering functions for different env
let template, render
if (isProd) {
template = fs.readFileSync(resolve('./dist/client/index.html'), 'utf-8')
render = (await import('./dist/server/entry-server.js')).render
} else {
template = fs.readFileSync(resolve('index.html'), 'utf-8')
template = await vite.transformIndexHtml(url, template)
render = (await vite.ssrLoadModule('/src/entry-server.js')).render
}
const [appHtml, preloadLinks, piniaState] = await render(url, manifest)
// replace processed resources
const html = template
.replace(`<!--preload-links-->`, preloadLinks)
.replace(`<!--ssr-outlet-->`, appHtml)
.replace(`<!--pinia-state-->`, piniaState)
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
} catch (error) {
vite?.ssrFixStacktrace(error)
next()
}
})
return { app, isTest, isProd }
}
export default createServer