-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
67 lines (60 loc) · 1.82 KB
/
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import express, { Express, Request, Response } from "express";
import fs from "fs";
async function configProd(app: Express) {
app.use(
(await import("serve-static")).default("./dist/client", {
index: false, // don't send index.html as there's none
})
);
// @ts-ignore
const render = (await import("./dist/server/entry-server.js")).render;
// replace bootstrap script with compiled scripts
const bootstrap =
"/assets/" +
fs
.readdirSync("./dist/client/assets")
.filter((fn: string) => fn.includes("main") && fn.endsWith(".js"))[0];
app.use("*", (req, res) => render(req, res, bootstrap));
return app;
}
async function configDev(app: Express) {
const cwd = process.cwd();
// dev mode, configure vite as middleware
const vite = await (
await import("vite")
).createServer({
root: cwd,
server: {
middlewareMode: true,
hmr: true,
},
appType: "custom",
});
app.use(vite.middlewares);
const renderer = async (req: Request, res: Response) => {
// in dev mode, we will try to load the render function for every request,
// so that editing the entry-server file take effect without restart server.
try {
const render = (await vite.ssrLoadModule("./entry-server.tsx")).render;
render(req, res, `/src/main.tsx`);
} catch (err) {
const e = err as Error;
vite.ssrFixStacktrace(e);
console.log(e.stack);
res.status(500).end(e.stack);
}
};
app.use("*", renderer);
return app;
}
const isProd = process.env.NODE_ENV === "production";
const port = process.env.PORT || (isProd ? 4173 : 5173);
const app = express();
const config = isProd ? configProd : configDev;
config(app)
.then((app) => {
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`);
});
})
.catch(console.error);