tars / server /static.ts
surekim's picture
Update server/static.ts
a059179 verified
Raw History Blame Contribute Delete
1.42 kB
import express, { type Express } from "express";
import fs from "fs";
import path, { dirname } from "path";
import { fileURLToPath } from "url";
// [์ˆ˜์ •] __dirname์„ ES ๋ชจ๋“ˆ ๋ฐฉ์‹์— ๋งž๊ฒŒ ์•ˆ์ „ํ•˜๊ฒŒ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค.
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export function serveStatic(app: Express) {
// [์ˆ˜์ •] ํ”„๋กœ์ ํŠธ ๊ตฌ์กฐ์— ๋งž์ถฐ ๋นŒ๋“œ๋œ public ํด๋”์˜ ๊ฒฝ๋กœ๋ฅผ ์ •ํ™•ํžˆ ์žก์Šต๋‹ˆ๋‹ค.
// ๋ณดํ†ต server ํด๋”์˜ ํ•œ ๋‹จ๊ณ„ ์œ„(..)์— public์ด ์œ„์น˜ํ•ฉ๋‹ˆ๋‹ค.
const distPath = path.resolve(__dirname, "..", "public");
if (!fs.existsSync(distPath)) {
console.error(`๋นŒ๋“œ ํด๋”๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค: ${distPath}`);
// ์„œ๋ฒ„๊ฐ€ ์•„์˜ˆ ์ฃฝ์ง€ ์•Š๋„๋ก ์—๋Ÿฌ๋ฅผ ๋˜์ง€๋Š” ๋Œ€์‹  ๋กœ๊ทธ๋ฅผ ๋‚จ๊น๋‹ˆ๋‹ค.
return;
}
// 1. ์ •์  ํŒŒ์ผ(์ด๋ฏธ์ง€, JS, CSS) ์„œ๋น™
app.use(express.static(distPath));
// 2. [์ˆ˜์ •] ๋ชจ๋“  ์š”์ฒญ์„ index.html๋กœ ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ (SPA ๋ฐฉ์‹)
// ๋น„ํ‘œ์ค€ ๋ฌธ๋ฒ•์ธ "/{*path}" ๋Œ€์‹  ํ‘œ์ค€ ๋ฌธ๋ฒ•์ธ "*"์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
app.get("*", (req, res) => {
// API ์š”์ฒญ์ด ์•„๋‹ ๊ฒฝ์šฐ์—๋งŒ index.html์„ ๋ณด๋ƒ…๋‹ˆ๋‹ค.
if (!req.path.startsWith("/api")) {
res.sendFile(path.resolve(distPath, "index.html"), (err) => {
if (err) {
res.status(404).send("index.html ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.");
}
});
}
});
}