-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathserver.ts
115 lines (87 loc) · 3.1 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
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
import * as fs from 'node:fs';
import * as path from 'node:path';
import { fileURLToPath } from 'node:url';
import express from 'express';
import dotenv from 'dotenv'
import api from './server/app.js';
dotenv.config()
const __dirname: string = path.dirname(fileURLToPath(import.meta.url));
const isTest = process.env.VITEST;
const isProd = process.env.NODE_ENV === 'production'
const root: string = process.cwd();
const resolve = (_path: string) => path.resolve(__dirname, _path);
const indexProd: string = isProd
? fs.readFileSync(resolve('client/index.html'), 'utf-8')
: ''
const createServer = async () => {
const app = express();
let vite: any;
if (!isProd) {
vite = await (await import('vite')).createServer({
root,
logLevel: isTest ? 'error' : 'info',
server: {
middlewareMode: true,
watch: {
usePolling: true,
interval: 100
}
},
appType: "custom"
})
app.use(vite.middlewares)
}
if (isProd) {
app.use((await import('compression')).default())
app.use(
(await import('serve-static')).default(resolve('./client'), {
index: false
})
)
}
// api routes
app.use('/api', api.router)
app.use('*', async (req, res) => {
try {
const url = req.originalUrl;
let template, render;
if (!isProd) {
template = fs.readFileSync(resolve('index.html'), 'utf8')
template = await vite.transformIndexHtml(url, template)
render = (await vite.ssrLoadModule('/src/entry-server.tsx')).default.render;
}
if (isProd) {
template = indexProd;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
render = (await import('../entry/entry-server.js')).default.render;
}
const context: any = {};
const appHtml = await render(req)
const { helmet } = appHtml;
if (context.url) return res.redirect(301, context.url);
let html = template.replace('<!--app-html-->', appHtml.html)
const helmetData = `
${helmet.title.toString()}
${helmet.meta.toString()}
${helmet.link.toString()}
${helmet.style.toString()}
`
html = html.replace('<!--app-head-->', helmetData)
html = html.replace('<!--app-scripts-->', helmet.script.toString())
res.status(200).set({ "Content-Type": "text/html" }).end(html)
} catch (e: any) {
!isProd && vite.ssrFixStacktrace(e)
console.log(e.stack)
res.status(500).end(e.stack)
}
})
return { app, vite }
}
if (!isTest) {
createServer().then(({ app }) => {
app.listen(process.env.PORT || 3000, () => {
console.log(`Server running on http://localhost:${process.env.PORT || 3000}`);
})
})
}