-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
91 lines (80 loc) · 2.61 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
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
// server.js
import fs from "node:fs/promises";
import path from "node:path";
import url from "node:url";
import express from "express";
// Constants
const isProduction = process.env.NODE_ENV === "production";
const isStatic = process.env.STATIC === "true";
const port = process.env.PORT || 5173;
const base = process.env.BASE || "/";
const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
const resolve = (p) => path.resolve(__dirname, p);
// Cached production assets
const templateHtml = isProduction
? await fs.readFile(`./dist/${isStatic ? "static" : "client"}/index.html`, "utf-8")
: "";
// Cached production manifest
const manifest = isProduction
? JSON.parse(
await fs.readFile(
resolve("dist/client/.vite/ssr-manifest.json"),
"utf-8",
),
)
: {};
// Create http server
const app = express();
// Add Vite or respective production middlewares
/** @type {import('vite').ViteDevServer | undefined} */
let vite;
if (!isProduction) {
const { createServer } = await import("vite");
vite = await createServer({
server: { middlewareMode: true },
appType: "custom",
base,
});
app.use(vite.middlewares);
} else {
const compression = (await import("compression")).default;
const sirv = (await import("sirv")).default;
app.use(compression());
app.use(base, sirv(`./dist/${isStatic ? "static" : "client"}`, { extensions: [] }));
}
// Serve HTML
app.use("*all", async (req, res) => {
try {
const url = req.originalUrl.replace(base, "");
/** @type {string} */
let template;
/** @type {import('./src/entry-server.tsx').render} */
let render;
if (!isProduction) {
// Always read fresh template in development
template = await fs.readFile("./index.html", "utf-8");
template = await vite.transformIndexHtml(url, template);
render = (await vite.ssrLoadModule("/src/entry-server.tsx")).render;
} else {
template = templateHtml;
render = (await import("./dist/server/entry-server.js")).render;
}
let html = templateHtml;
if (!isStatic) {
const rendered = await render(url, manifest);
html = template
.replace(`<!--preload-links-->`, rendered.preloadLinks ?? "")
.replace(`<!--app-head-->`, rendered.head ?? "")
.replace(`<!--app-html-->`, rendered.html ?? "");
}
res.status(200).set({ "Content-Type": "text/html" }).send(html);
} catch (e) {
vite?.ssrFixStacktrace(e);
console.log(e.stack);
res.status(500).end(e.stack);
}
});
// Start http server
app.listen(port, () => {
console.log(`Server ${isStatic ? "SSG" : "SSR"} mode started at http://localhost:${port}`);
});