chore: add server/vite.ts
This commit is contained in:
parent
0bb38fa225
commit
dbc8003a08
1 changed files with 59 additions and 0 deletions
59
server/vite.ts
Normal file
59
server/vite.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { type Express } from "express";
|
||||
import { createServer as createViteServer, createLogger } from "vite";
|
||||
import { type Server } from "http";
|
||||
import viteConfig from "../vite.config";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
const viteLogger = createLogger();
|
||||
|
||||
export async function setupVite(server: Server, app: Express) {
|
||||
const vite = await createViteServer({
|
||||
...viteConfig,
|
||||
configFile: false,
|
||||
customLogger: {
|
||||
...viteLogger,
|
||||
error: (msg, options) => {
|
||||
viteLogger.error(msg, options);
|
||||
process.exit(1);
|
||||
},
|
||||
},
|
||||
server: {
|
||||
middlewareMode: true,
|
||||
hmr: { server, path: "/vite-hmr" },
|
||||
allowedHosts: true as const,
|
||||
},
|
||||
appType: "custom",
|
||||
});
|
||||
|
||||
app.use(vite.middlewares);
|
||||
|
||||
app.use("/{*path}", async (req, res, next) => {
|
||||
const url = req.originalUrl;
|
||||
try {
|
||||
const clientTemplate = path.resolve(import.meta.dirname, "..", "client", "index.html");
|
||||
let template = await fs.promises.readFile(clientTemplate, "utf-8");
|
||||
template = await vite.transformIndexHtml(url, template);
|
||||
res.status(200).set({ "Content-Type": "text/html" }).end(template);
|
||||
} catch (e: any) {
|
||||
vite.ssrFixStacktrace(e);
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function serveStatic(app: Express) {
|
||||
const distPath = path.resolve(import.meta.dirname, "..", "dist", "public");
|
||||
if (!fs.existsSync(distPath)) {
|
||||
throw new Error(`Production build not found at ${distPath}. Run 'npm run build' first.`);
|
||||
}
|
||||
app.use(
|
||||
require("express").static(distPath, {
|
||||
maxAge: "1y",
|
||||
index: false,
|
||||
})
|
||||
);
|
||||
app.use("/{*path}", (_req, res) => {
|
||||
res.sendFile(path.resolve(distPath, "index.html"));
|
||||
});
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue