-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
50 lines (43 loc) · 1.25 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
const express = require("express");
const { createServer: createViteServer } = require("vite");
const path = require("path");
async function createServer() {
const app = express();
// Create Vite server in middleware mode
const vite = await createViteServer({
server: {
middlewareMode: true,
},
});
// Use Vite's connect instance as middleware
app.use(vite.middlewares);
// Handle all routes with index.html
app.get("*", async (req, res) => {
try {
const url = req.originalUrl;
const template = await vite.transformIndexHtml(
url,
'<div id="app"></div>'
);
const { render } = await vite.ssrLoadModule("/src/App.jsx");
const appHtml = await render(url);
const html = template.replace(
'<div id="app"></div>',
`<div id="app">${appHtml}</div>`
);
res.status(200).set({ "Content-Type": "text/html" }).end(html);
} catch (error) {
vite.ssrFixStacktrace(error);
console.error(error);
res.status(500).end(error.message);
}
});
// Start the server
app.listen(3000, () => {
console.log("Server started on port 3000");
});
}
createServer().catch((error) => {
console.error("Error starting server:", error);
process.exit(1);
});