-
Notifications
You must be signed in to change notification settings - Fork 6
/
plugin-dev-server.ts
51 lines (41 loc) · 1.25 KB
/
plugin-dev-server.ts
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
import fs from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { Connect, Plugin, ViteDevServer } from 'vite';
import type TRender from './demo/entry-server';
async function ssrMiddleware(
vite: ViteDevServer,
req: Connect.IncomingMessage,
res: ServerResponse<IncomingMessage>
) {
const template = await vite.transformIndexHtml(
req.url as string,
fs.readFileSync(`${__dirname}/index.html`, 'utf8'),
req.originalUrl
);
const render = (await vite.ssrLoadModule('/demo/entry-server.ts'))
.default as typeof TRender;
const { appHtml, css } = await render(req.originalUrl as string, vite);
res.statusCode = 200;
res.setHeader('content-type', 'text/html');
res.end(
template
.replace('<!--dev-ssr-css-->', css)
.replace('<!--app-html-->', appHtml)
);
}
export default function devSSRPlugin(): Plugin {
return {
name: 'dev-ssr',
configureServer(vite) {
const { logger } = vite.config;
return () =>
vite.middlewares.use((req, res, next) => {
ssrMiddleware(vite, req, res).catch((e: Error) => {
vite.ssrFixStacktrace(e);
logger.error(e.stack || e.message);
next(e);
});
});
},
};
}