-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathserver.mjs
More file actions
120 lines (105 loc) · 3.19 KB
/
server.mjs
File metadata and controls
120 lines (105 loc) · 3.19 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// @ts-check
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import express from 'express'
import open from 'open'
const isTest = process.env.VITEST
const PORT = process.env.PORT || 5173
export async function createServer(
root = process.cwd(),
isProd = process.env.NODE_ENV === 'production',
hmrPort = undefined,
) {
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const resolve = p => path.resolve(__dirname, p)
const indexProd = isProd ? fs.readFileSync(resolve('dist/client/index.html'), 'utf-8') : ''
const manifest = isProd ? JSON.parse(fs.readFileSync(resolve('dist/client/ssr-manifest.json'), 'utf-8')) : {}
const app = express()
/**
* @type {import('vite').ViteDevServer | null}
*/
let vite = null
if (!isProd) {
vite = await (
await import('vite')
).createServer({
// base: '/',
root,
clearScreen: false,
logLevel: isTest ? 'error' : 'info',
server: {
open: true,
middlewareMode: true,
hmr: {
port: hmrPort,
},
},
appType: 'custom',
})
// use vite's connect instance as middleware
app.use(vite.middlewares)
} else {
app.use((await import('compression')).default())
app.use(
'/',
(await import('serve-static')).default(resolve('dist/client'), {
index: false,
}),
)
}
app.use('*', async (req, res) => {
try {
const url = req.originalUrl
let template, render
// vite is always there in dev
if (!isProd && vite) {
// always read fresh template in dev
template = fs.readFileSync(resolve('index.html'), 'utf-8')
template = await vite.transformIndexHtml(url, template)
render = (await vite.ssrLoadModule('/src/entry-server.ts')).render
} else {
template = indexProd
// @ts-ignore
render = (await import('./dist/server/entry-server.mjs')).render
}
if ('no-ssr' in req.query) {
return res.status(200).set({ 'Content-Type': 'text/html' }).end(template)
}
const [appHtml, preloadLinks, state] = await render(url, manifest)
const html = template
.replace(`<!--preload-links-->`, preloadLinks)
.replace(`<!--app-html-->`, appHtml)
.replace(
`<!--pinia-state-->`,
`<script>` +
// add pinia state
`window.__PINIA_STATE__ = ${JSON.stringify(state)}` +
`</script>`,
)
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
} catch (e) {
vite && vite.ssrFixStacktrace(e)
const debugURL = new URL(req.originalUrl, `http://localhost:${PORT}`)
debugURL.searchParams.set('no-ssr', '')
res
.status(500)
.end(
`<!DOCTYPE html><p><a href="${debugURL.href}">Reload without SSR</a> to debug locally.</p><br><pre>` +
e.stack +
`</pre>`,
)
}
})
return { app, vite }
}
if (!isTest) {
createServer().then(({ app }) =>
app.listen(PORT, () => {
console.log(`http://localhost:${PORT}`)
if (process.argv.includes('--open')) {
open(`http://localhost:${PORT}`)
}
}),
)
}