-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathserver.js
More file actions
71 lines (57 loc) · 1.61 KB
/
server.js
File metadata and controls
71 lines (57 loc) · 1.61 KB
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
import fs from "fs";
import path from "path";
import { createApp } from "h3";
import { createServer as createViteServer } from "vite";
import { listen } from "listhen";
import sirv from "sirv";
const DEV_ENV = "development";
const bootstrap = async () => {
const app = createApp();
let vite;
if (process.env.NODE_ENV === DEV_ENV) {
vite = await createViteServer({
server: { middlewareMode: true },
appType: "custom",
});
app.use(vite.middlewares);
} else {
app.use(sirv("dist/client", {
gzip: true,
})
);
}
app.use("*", async (req, res, next) => {
const url = req.originalUrl;
let template, render;
try {
if (process.env.NODE_ENV === DEV_ENV) {
template = fs.readFileSync(path.resolve("./index.html"), "utf-8");
template = await vite.transformIndexHtml(url, template);
render = (await vite.ssrLoadModule("/src/entry-server.tsx")).render;
} else {
template = fs.readFileSync(
path.resolve("dist/client/index.html"),
"utf-8"
);
render = (await import("./dist/server/entry-server.js")).render;
}
const appHtml = await render({ path: url });
const html = template.replace(`<!--ssr-outlet-->`, appHtml);
res.statusCode = 200;
res.setHeader("Content-Type", "text/html").end(html);
} catch (error) {
vite.ssrFixStacktrace(error);
next(error);
}
});
return { app };
};
bootstrap()
.then(async ({ app }) => {
try {
await listen(app, { port: 3333 });
} catch (error) {
throw error;
}
})
.catch(console.error);