
Replit-Commit-Author: Agent Replit-Commit-Session-Id: e931b5ab-041b-42e7-baf1-50017869cef6 Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/e19c6a51-7e4c-4bb8-a6a6-46dc00f0ec99/3a46e308-0211-4c54-a52b-c291792321ef.jpg
89 lines
2.3 KiB
TypeScript
89 lines
2.3 KiB
TypeScript
import express, { type Express } from "express";
|
|
import fs from "fs";
|
|
import path, { dirname } from "path";
|
|
import { fileURLToPath } from "url";
|
|
import { createServer as createViteServer, createLogger } from "vite";
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = dirname(__filename);
|
|
import { type Server } from "http";
|
|
import viteConfig from "../vite.config";
|
|
import { nanoid } from "nanoid";
|
|
|
|
const viteLogger = createLogger();
|
|
|
|
export function log(message: string, source = "express") {
|
|
const formattedTime = new Date().toLocaleTimeString("en-US", {
|
|
hour: "numeric",
|
|
minute: "2-digit",
|
|
second: "2-digit",
|
|
hour12: true,
|
|
});
|
|
|
|
console.log(`${formattedTime} [${source}] ${message}`);
|
|
}
|
|
|
|
export async function setupVite(app: Express, server: Server) {
|
|
const serverOptions = {
|
|
middlewareMode: true,
|
|
hmr: { server },
|
|
allowedHosts: true,
|
|
};
|
|
|
|
const vite = await createViteServer({
|
|
...viteConfig,
|
|
configFile: false,
|
|
customLogger: {
|
|
...viteLogger,
|
|
error: (msg, options) => {
|
|
viteLogger.error(msg, options);
|
|
process.exit(1);
|
|
},
|
|
},
|
|
server: serverOptions,
|
|
appType: "custom",
|
|
});
|
|
|
|
app.use(vite.middlewares);
|
|
app.use("*", async (req, res, next) => {
|
|
const url = req.originalUrl;
|
|
|
|
try {
|
|
const clientTemplate = path.resolve(
|
|
__dirname,
|
|
"..",
|
|
"client",
|
|
"index.html",
|
|
);
|
|
|
|
// always reload the index.html file from disk incase it changes
|
|
let template = await fs.promises.readFile(clientTemplate, "utf-8");
|
|
template = template.replace(
|
|
`src="/src/main.tsx"`,
|
|
`src="/src/main.tsx?v=${nanoid()}"`,
|
|
);
|
|
const page = await vite.transformIndexHtml(url, template);
|
|
res.status(200).set({ "Content-Type": "text/html" }).end(page);
|
|
} catch (e) {
|
|
vite.ssrFixStacktrace(e as Error);
|
|
next(e);
|
|
}
|
|
});
|
|
}
|
|
|
|
export function serveStatic(app: Express) {
|
|
const distPath = path.resolve(__dirname, "public");
|
|
|
|
if (!fs.existsSync(distPath)) {
|
|
throw new Error(
|
|
`Could not find the build directory: ${distPath}, make sure to build the client first`,
|
|
);
|
|
}
|
|
|
|
app.use(express.static(distPath));
|
|
|
|
// fall through to index.html if the file doesn't exist
|
|
app.use("*", (_req, res) => {
|
|
res.sendFile(path.resolve(distPath, "index.html"));
|
|
});
|
|
}
|