|
| 1 | +import type { RenderFunction } from "./entry-server"; |
| 2 | +import fs from "fs"; |
| 3 | +import path from "path"; |
| 4 | +import express from "express"; |
| 5 | +import { fileURLToPath } from "node:url"; |
| 6 | +import { createServer as createViteServer } from "vite"; |
| 7 | + |
| 8 | +const __dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 9 | + |
| 10 | +function injectContent(head: string, content: string, template: string) { |
| 11 | + return template |
| 12 | + .replace(`</head>`, `${head}</head>`) |
| 13 | + .replace(`<div id="root"></div>`, `<div id="root">${content}</div>`); |
| 14 | +} |
| 15 | + |
| 16 | +async function createServer() { |
| 17 | + const app = express(); |
| 18 | + |
| 19 | + // Create Vite server in middleware mode and configure the app type as |
| 20 | + // 'custom', disabling Vite's own HTML serving logic so parent server |
| 21 | + // can take control |
| 22 | + const vite = await createViteServer({ |
| 23 | + server: { middlewareMode: true }, |
| 24 | + appType: "custom", |
| 25 | + }); |
| 26 | + |
| 27 | + // use vite's connect instance as middleware |
| 28 | + // if you use your own express router (express.Router()), you should use router.use |
| 29 | + app.use(vite.middlewares); |
| 30 | + |
| 31 | + app.get("*", async (req, res, next) => { |
| 32 | + try { |
| 33 | + const url: string = req.originalUrl.split(/\?#/)[0] || "/"; |
| 34 | + |
| 35 | + // // 1. Read and apply Vite HTML transforms. This injects the Vite HMR client, and |
| 36 | + // // also applies HTML transforms from Vite plugins, e.g. global preambles |
| 37 | + // // from @vitejs/plugin-react |
| 38 | + const template: string = await vite.transformIndexHtml( |
| 39 | + req.originalUrl, |
| 40 | + fs.readFileSync(path.resolve(__dirname, "..", "index.html"), "utf-8") |
| 41 | + ); |
| 42 | + |
| 43 | + // 2. Load the server entry. vite.ssrLoadModule automatically transforms |
| 44 | + // your ESM source code to be usable in Node.js! There is no bundling |
| 45 | + // required, and provides efficient invalidation similar to HMR. |
| 46 | + const { render } = (await vite.ssrLoadModule("./src/entry-server")) as { |
| 47 | + render: RenderFunction; |
| 48 | + }; |
| 49 | + |
| 50 | + const rendered = await render(url); |
| 51 | + |
| 52 | + return res |
| 53 | + .status(rendered.status) |
| 54 | + .set({ "Content-Type": "text/html" }) |
| 55 | + .send(injectContent(rendered.head, rendered.content, template)); |
| 56 | + } catch (e) { |
| 57 | + // If an error is caught, let Vite fix the stack trace so it maps back to |
| 58 | + // your actual source code. |
| 59 | + if (e instanceof Error) { |
| 60 | + vite.ssrFixStacktrace(e); |
| 61 | + } |
| 62 | + |
| 63 | + next(e); |
| 64 | + } |
| 65 | + }); |
| 66 | + |
| 67 | + app.listen(5173, () => { |
| 68 | + console.log(`Server listening on http://localhost:5173`); |
| 69 | + }); |
| 70 | +} |
| 71 | + |
| 72 | +createServer(); |
0 commit comments