-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
123 lines (108 loc) · 3.39 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import fs from 'node:fs/promises';
import express from 'express';
import https from 'https';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { readFileSync } from 'node:fs';
import { loadEnv } from 'vite';
import { createProxyMiddleware } from 'http-proxy-middleware';
import { getProxyConfig } from './proxy.config.js';
const env = loadEnv(process.env.NODE_ENV, process.cwd(), '');
let isHTTPS = parseBoolean(env.HTTPS);
const isDev = env.NODE_ENV === 'development';
const isDocker = parseBoolean(env.IS_DOCKER);
// const isSSR = parseBoolean(env.VITE_SSR);
// =====================================================
let hostname = env.HOST || '0.0.0.0';
let port = parseInt(env.PORT);
if (!port) port = isHTTPS ? 443 : isDev ? 5173 : 4173;
// =====================================================
if (isDocker) {
port = 3000;
hostname = '0.0.0.0';
isHTTPS = false;
}
const base = env.BASE || '/';
const certDir = isHTTPS ? resolve(dirname(fileURLToPath(import.meta.url)), '.certs') : '';
// Cached production assets
const templateHtml = !isDev ? await fs.readFile('./dist/client/index.html', 'utf-8') : '';
const ssrManifest = !isDev ? await fs.readFile('./dist/client/.vite/ssr-manifest.json', 'utf-8') : undefined;
// Create http server or https
const app = express();
// Add proxies
const proxies = getProxyConfig(env);
proxies.forEach((proxy) => {
const { pathUrl, ...rest } = proxy;
app.use(
pathUrl,
createProxyMiddleware({
...rest,
}),
);
});
// Add Vite or respective production middlewares
let vite;
if (isDev) {
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/client', { extensions: [] }));
}
// Serve HTML
app.use('*', async (req, res) => {
try {
const url = req.originalUrl.replace(base, '');
let template;
let render;
if (isDev) {
// 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;
}
const rendered = await render(url, ssrManifest);
const html = template
.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);
}
});
// if (isHTTPS) {
// https
// .createServer(
// {
// key: readFileSync(resolve(certDir, './cert.key')),
// cert: readFileSync(resolve(certDir, './cert.crt')),
// },
// app,
// )
// .listen(port, () => {
// console.log(`HTTPS Server is running at https://${hostname}:${port}`);
// });
// } else {
// // Start http server
// app.listen(port, () => {
// console.log(`Server started at http://localhost:${port}`);
// });
// }
app.listen(port, hostname, () => {
console.log(`Server started at http://${hostname}:${port}`);
});
function parseBoolean(str) {
return (str || '').trim().toLowerCase() === 'true';
}