31 lines
958 B
TypeScript
31 lines
958 B
TypeScript
import express from 'express';
|
|
import type { Express } from 'express';
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
|
|
export function serveStatic(app: Express) {
|
|
// In production, dist/public is at the same level as index.cjs
|
|
const distPath = path.resolve(__dirname, "..", "public");
|
|
if (!fs.existsSync(distPath)) {
|
|
// Fallback: check cwd
|
|
const cwdPath = path.resolve(process.cwd(), "dist", "public");
|
|
if (fs.existsSync(cwdPath)) {
|
|
app.use(express.static(cwdPath));
|
|
app.use("/{*path}", (_req, res) => {
|
|
res.sendFile(path.resolve(cwdPath, "index.html"));
|
|
});
|
|
return;
|
|
}
|
|
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("/{*path}", (_req, res) => {
|
|
res.sendFile(path.resolve(distPath, "index.html"));
|
|
});
|
|
}
|