-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev_server.js
More file actions
50 lines (40 loc) · 1.41 KB
/
Copy pathdev_server.js
File metadata and controls
50 lines (40 loc) · 1.41 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
const axios = require('axios');
const dotenv = require('dotenv');
const express = require('express');
const http = require('http');
const { setupRoutes } = require('./api/routes.js');
const { createServer: createViteServer } = require('vite');
dotenv.config();
const startServer = async () => {
const app = express();
const port = process.env.PORT ? Number(process.env.PORT) : 3001;
const httpServer = http.createServer(app);
// Create Vite server in middleware mode, reusing the Express HTTP server
// for HMR's WebSocket instead of letting Vite open its own on the default
// port — otherwise every worktree's example app collides on that port.
const vite = await createViteServer({
server: { middlewareMode: true, ws: { server: httpServer } },
});
app.use(express.json({ limit: '50mb' }));
// API route example
setupRoutes(app);
app.use(vite.middlewares);
// Serve index.html (SSR or SPA fallback)
app.use(async (req, res, next) => {
try {
const url = req.originalUrl;
const template = await vite.transformIndexHtml(
url,
'<!DOCTYPE html><html><body><div id="app"></div></body></html>',
);
res.status(200).set({ 'Content-Type': 'text/html' }).send(template);
} catch (e) {
vite.ssrFixStacktrace(e);
next(e);
}
});
httpServer.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
};
startServer();