-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathserver.js
More file actions
73 lines (64 loc) · 2.17 KB
/
server.js
File metadata and controls
73 lines (64 loc) · 2.17 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
72
73
import { createRsbuild, loadConfig } from '@rsbuild/core';
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const isDev = process.env.NODE_ENV !== 'production';
async function startServer() {
if (isDev) {
const config = await loadConfig();
const rsbuild = await createRsbuild({
rsbuildConfig: config.content,
});
const devServer = await rsbuild.createDevServer();
app.use(devServer.middlewares);
app.use(async (req, res, next) => {
try {
const tryLoadBundle = async (entryName) => {
try {
return await devServer.environments.node.loadBundle(entryName);
} catch (error) {
if (error instanceof Error && error.message.includes("Can't find entry")) {
return null;
}
throw error;
}
};
const bundle = /** @type {import("./server/index.js")} */ (
(await tryLoadBundle('static/js/app')) ?? (await tryLoadBundle('app'))
);
await bundle.app(req, res, next);
} catch (e) {
next(e);
}
});
const port = Number.parseInt(process.env.PORT || '3000', 10);
const server = app.listen(port, () => {
console.log(`Development server is running on http://localhost:${port}`);
devServer.afterListen();
});
devServer.connectWebSocket({ server });
} else {
// Production mode
app.use(express.static(path.join(__dirname, 'build/client'), {
index: false
}));
// Load the server bundle
const serverBundle = await import('./build/server/static/js/app.js');
// Mount the server app after static file handling
app.use(async (req, res, next) => {
try {
await /** @type {any} */(serverBundle.default).app(req, res, next);
} catch (e) {
next(e);
}
});
const port = Number.parseInt(process.env.PORT || '3000', 10);
app.listen(port, () => {
console.log(`Production server is running on http://localhost:${port}`);
});
}
}
startServer().catch(console.error);