vite.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import express, { type Express } from "express";
  2. import fs from "fs";
  3. import { type Server } from "http";
  4. import { nanoid } from "nanoid";
  5. import path from "path";
  6. import { createServer as createViteServer } from "vite";
  7. import viteConfig from "../../vite.config";
  8. export async function setupVite(app: Express, server: Server) {
  9. const serverOptions = {
  10. middlewareMode: true,
  11. hmr: { server },
  12. allowedHosts: true as const,
  13. };
  14. const vite = await createViteServer({
  15. ...viteConfig,
  16. configFile: false,
  17. server: serverOptions,
  18. appType: "custom",
  19. });
  20. app.use(vite.middlewares);
  21. app.use("*", async (req, res, next) => {
  22. const url = req.originalUrl;
  23. try {
  24. const clientTemplate = path.resolve(
  25. import.meta.dirname,
  26. "../..",
  27. "client",
  28. "index.html"
  29. );
  30. // always reload the index.html file from disk incase it changes
  31. let template = await fs.promises.readFile(clientTemplate, "utf-8");
  32. template = template.replace(
  33. `src="/src/main.tsx"`,
  34. `src="/src/main.tsx?v=${nanoid()}"`
  35. );
  36. const page = await vite.transformIndexHtml(url, template);
  37. res.status(200).set({ "Content-Type": "text/html" }).end(page);
  38. } catch (e) {
  39. vite.ssrFixStacktrace(e as Error);
  40. next(e);
  41. }
  42. });
  43. }
  44. export function serveStatic(app: Express) {
  45. const distPath =
  46. process.env.NODE_ENV === "development"
  47. ? path.resolve(import.meta.dirname, "../..", "dist", "public")
  48. : path.resolve(import.meta.dirname, "public");
  49. if (!fs.existsSync(distPath)) {
  50. console.error(
  51. `Could not find the build directory: ${distPath}, make sure to build the client first`
  52. );
  53. }
  54. app.use(express.static(distPath));
  55. // fall through to index.html if the file doesn't exist
  56. app.use("*", (_req, res) => {
  57. res.sendFile(path.resolve(distPath, "index.html"));
  58. });
  59. }