Fix: Remove import.meta from static.ts for CJS compatibility
- Use process.cwd() first, then __dirname fallback - No more import.meta.url in CJS bundlemaster
parent
1877bb7aa7
commit
45340d8f85
|
|
@ -2,28 +2,29 @@ import express from 'express';
|
||||||
import type { Express } from 'express';
|
import type { Express } from 'express';
|
||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
|
||||||
const __dirname = path.dirname(__filename);
|
|
||||||
|
|
||||||
export function serveStatic(app: Express) {
|
export function serveStatic(app: Express) {
|
||||||
// In production CJS bundle, __dirname points to the compiled file
|
// In production CJS bundle, we check cwd first (PM2 working directory)
|
||||||
// so we check both the bundle-relative path and cwd
|
|
||||||
const bundleDistPath = path.resolve(__dirname, "..", "public");
|
|
||||||
const cwdDistPath = path.resolve(process.cwd(), "dist", "public");
|
const cwdDistPath = path.resolve(process.cwd(), "dist", "public");
|
||||||
const distPath = fs.existsSync(cwdDistPath) ? cwdDistPath : bundleDistPath;
|
if (fs.existsSync(cwdDistPath)) {
|
||||||
|
app.use(express.static(cwdDistPath));
|
||||||
if (!fs.existsSync(distPath)) {
|
app.use("/{*path}", (_req, res) => {
|
||||||
throw new Error(
|
res.sendFile(path.resolve(cwdDistPath, "index.html"));
|
||||||
`Could not find the build directory: ${distPath}, make sure to build the client first`,
|
});
|
||||||
);
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
app.use(express.static(distPath));
|
// Fallback: check relative to this file
|
||||||
|
const bundleDistPath = path.resolve(__dirname, "..", "public");
|
||||||
|
if (fs.existsSync(bundleDistPath)) {
|
||||||
|
app.use(express.static(bundleDistPath));
|
||||||
|
app.use("/{*path}", (_req, res) => {
|
||||||
|
res.sendFile(path.resolve(bundleDistPath, "index.html"));
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// fall through to index.html if the file doesn't exist
|
throw new Error(
|
||||||
app.use("/{*path}", (_req, res) => {
|
`Could not find the build directory. Checked: ${cwdDistPath}, ${bundleDistPath}`,
|
||||||
res.sendFile(path.resolve(distPath, "index.html"));
|
);
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue