61 lines
1.7 KiB
TypeScript
61 lines
1.7 KiB
TypeScript
import { type Express } from "express";
|
|
import { createServer as createViteServer, createLogger } from "vite";
|
|
import { type Server } from "http";
|
|
import { createRequire } from "module";
|
|
import viteConfig from "../vite.config";
|
|
import fs from "fs";
|
|
import path from "path";
|
|
import express from "express";
|
|
|
|
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(
|
|
express.static(distPath, {
|
|
maxAge: "1y",
|
|
index: false,
|
|
})
|
|
);
|
|
app.use("/{*path}", (_req, res) => {
|
|
res.sendFile(path.resolve(distPath, "index.html"));
|
|
});
|
|
}
|