forked from mengdu/vite-react-ssr
-
Notifications
You must be signed in to change notification settings - Fork 3
/
vite-handle.js
175 lines (161 loc) · 3.93 KB
/
vite-handle.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
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// @ts-check
const fs = require('fs')
const { IncomingMessage } = require('http')
const path = require('path')
const isTest = process.env.NODE_ENV === 'test' || !!process.env.VITE_TEST_BUILD
const { Helmet } = require('react-helmet')
function queryStringToObject(query) {
const result = query.match(/\?(.*)/)
if (!result) return {}
return Object.fromEntries(new URLSearchParams(result[1]))
}
async function createViteHandle({
root = process.cwd(),
dev = true,
index,
dist,
}) {
/**
* @type {import('vite').ViteDevServer}
*/
let vite = null
let staticServe = null
const indexHTML = fs.readFileSync(index, 'utf-8')
if (dev) {
vite = await require('vite').createServer({
root,
logLevel: isTest ? 'error' : 'info',
server: {
middlewareMode: true,
},
})
} else {
staticServe = require('serve-static')(path.resolve(dist, 'client'), {
index: false,
})
}
return async (req, res) => {
if (dev) {
vite.middlewares(req, res, () => {
handleRender(req, res, {
template: indexHTML,
dev,
vite,
})
})
} else {
staticServe(req, res, () => {
handleRender(req, res, {
template: indexHTML,
dev,
vite,
dist,
})
})
}
}
}
/**
*
* @param {IncomingMessage} req
* @param {*} res
* @param {{template: any; dev: boolean; vite: import('vite').ViteDevServer;dist: string}} param2
* @returns
*/
async function handleRender(req, res, { template, dev, vite, dist }) {
try {
const url = req.url
let render
if (dev) {
// always read fresh template in dev
template = await vite.transformIndexHtml(url, template)
render = (await vite.ssrLoadModule('/src/entry-server.tsx')).render
} else {
render = require(path.resolve(dist, 'server/entry-server.js')).render
}
const context = {
isSSR: true,
query: req.query || queryStringToObject(req.url),
url: req.originalUrl,
req,
}
const { appHtml, propsData, redirect } = await render(url, context)
if (redirect) {
res.statusCode = 302
res.setHeader('Location', redirect)
res.end(`Location:${redirect}`)
return
}
const ssrDataText = JSON.stringify(propsData).replace(/\//g, '\\/')
const helmet = Helmet.renderStatic()
const html = template
.replace(
'<!--init-props-->',
`<script id="ssr-data" type="text/json">${ssrDataText}</script>`,
)
.replace(`<!--app-html-->`, appHtml)
.replace(
`<!--init-header-->`,
`${helmet.meta.toString()}${helmet.title.toString()}${helmet.script.toString()}`,
)
res.statusCode = 200
res.setHeader('Content-Type', 'text/html; utf-8')
res.end(html)
} catch (err) {
dev && vite.ssrFixStacktrace(err)
res.statusCode = 500
if (dev) {
console.error(err)
res.end(
`
<style>
html {
font-size: 14px;
}
main {
max-width: 800px;
margin: 5rem auto;
border: 3px solid red;
border-radius: 12px;
padding: 12px;
}
pre {
white-space: pre-line;
}
code {
display: block;
margin: 6px auto;
}
</style>
<main>
<p>${err.message}</p>
<p style="color: red;">Error at file: ${err.id}</p>
<div>
<p>
Frame at:
</p>
<pre>
${err.frame
?.split('\n')
.map((line) => `<code>${line}</code>`)
.join('')}
</pre>
</div>
<div>
<p>Output: </p>
<pre>
${err.pluginCode
?.split('\n')
.map((line) => `<code>${line}</code>`)
.join('')}
</pre>
</div>
</main>
`,
)
} else {
res.end('Server Error')
}
}
}
module.exports = createViteHandle