-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
50 lines (37 loc) · 1.2 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
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import express from 'express';
import { createServer as createViteServer } from 'vite';
const port = process.env.PORT || 5173;
const __dirname = path.dirname(fileURLToPath(import.meta.url));
async function createServer() {
const app = express();
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'custom',
build: {
ssr: true,
ssrEmitAssets: true,
},
});
app.use(vite.middlewares);
app.use('*', async (req, res, next) => {
const url = req.originalUrl;
try {
let template = fs.readFileSync(path.resolve(__dirname, 'index.html'), 'utf-8');
template = await vite.transformIndexHtml(url, template);
const { render } = await vite.ssrLoadModule('/src/entry-server.tsx');
const appHtml = await render(url);
const html = template.replace(`<!--ssr-outlet-->`, appHtml);
res.status(200).set({ 'Content-Type': 'text/html' }).end(html);
} catch (e) {
vite.ssrFixStacktrace(e);
next(e);
}
});
app.listen(port, () => {
console.log(`Server started at http://localhost:${port}`);
});
}
createServer();