feat(build): static export (index.html ต่อหน้า) สำหรับโฮสต์แบบไฟล์นิ่ง

- scripts/static-export.mjs: ดึง HTML ทุกหน้าจาก production server มาเป็นไฟล์นิ่ง
  · index.html, about/, for-cinemas/, for-film-lovers/, cinema/<slug>/ (ทุกโรงที่ไม่ hidden)
  · c/<slug>/ = หน้า redirect แบบ meta refresh + JS
  · คัดลอก .output/public (assets, รูป, manifest, sw, sitemap, robots) + 404.html
  · อ่าน slug จาก data/content/content.json (การ์ดหน้าแรก render ฝั่ง client จึงไม่มี link ใน HTML)
  · inject data-static-export-nav: ดักคลิก link ภายในเป็น full page load
    (static host ไม่มี endpoint ?_data= ของ React Router)
- package.json: script "export:static" · .gitignore: static-export/
- README: วิธี build/export/ทดสอบ + ข้อจำกัด (ไม่มี /admin, /api, 302, meta อบตอน export)
This commit is contained in:
Bkk1234 committed 2026-11-21 15:10:13 +07:00
1 parent 1cf1398ba4
commit 1c38d8e286
4 files changed
+169

No files matched your search

+146
View File
@@ -0,0 +1,146 @@
/**
* static-export — ดึง HTML ทุกหน้าจาก production server มาเป็นไฟล์ static (มี index.html)
*
* ใช้: node scripts/static-export.mjs [baseUrl] [outDir]
* baseUrl default http://127.0.0.1:8090
* outDir default ./static-export
*
* หมายเหตุสำคัญ: ไฟล์ HTML ที่ได้ "hydrate ได้" (ฟิลเตอร์/ค้นหา/แสดงเพิ่ม ทำงาน)
* แต่การคลิก link ไปหน้าอื่นจะเป็นการโหลดหน้าใหม่แบบเต็ม (ไม่มี `?_data=` บน static host)
*/
import fs from "node:fs";
import path from "node:path";
const BASE = (process.argv[2] ?? "http://127.0.0.1:8090").replace(/\/$/, "");
const OUT = process.argv[3] ?? "static-export";
const STATIC_ROUTES = [
"/",
"/about",
"/for-cinemas",
"/for-film-lovers",
"/sitemap.xml",
"/robots.txt",
];
async function get(urlPath) {
const res = await fetch(`${BASE}${urlPath}`, { redirect: "manual" });
const body = await res.text();
return {
status: res.status,
type: res.headers.get("content-type") ?? "",
body,
};
}
function writeRoute(routePath, body) {
const clean = routePath.split("?")[0].replace(/\/$/, "");
const isFile = /\.[a-z0-9]+$/i.test(clean);
const target = isFile
? path.join(OUT, clean)
: path.join(OUT, clean, "index.html");
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, body);
return target;
}
// 1) อ่าน slug จาก data/content/content.json (การ์ดในหน้าแรก render ฝั่ง client จึงหา link ใน HTML ไม่เจอ)
const contentPath = path.join("data", "content", "content.json");
const home = await get("/");
if (home.status !== 200) {
console.error(`หน้าแรกตอบ ${home.status} — server รันอยู่ไหม? (${BASE})`);
process.exit(1);
}
fs.rmSync(OUT, { recursive: true, force: true });
fs.mkdirSync(OUT, { recursive: true });
let slugs = [];
if (fs.existsSync(contentPath)) {
const content = JSON.parse(fs.readFileSync(contentPath, "utf8"));
slugs = (content.cinemas ?? [])
.filter((cinema) => cinema.hidden !== true && cinema.slug)
.map((cinema) => cinema.slug);
} else {
slugs = [...home.body.matchAll(/\/cinema\/([a-z0-9-]+)/g)].map((m) => m[1]);
}
const uniqueSlugs = [...new Set(slugs)];
const routes = [
...STATIC_ROUTES,
...uniqueSlugs.map((slug) => `/cinema/${slug}`),
];
let ok = 0;
const failed = [];
for (const route of routes) {
const res = await get(route);
if (res.status !== 200) {
failed.push(`${route} (${res.status})`);
continue;
}
writeRoute(route, res.body);
ok++;
}
// 2.5) static host ไม่มี endpoint `?_data=` ของ React Router
// → ดักคลิก link ภายในให้เป็นการโหลดหน้าเต็ม (ทุกหน้ามี HTML ของตัวเองอยู่แล้ว)
const STATIC_NAV_PATCH = `<script data-static-export-nav>(()=>{
document.addEventListener("click",(event)=>{
if(event.defaultPrevented||event.button!==0||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey)return;
const anchor=event.target instanceof Element?event.target.closest("a[href]"):null;
if(!anchor||!anchor.getAttribute("href").startsWith("/")||anchor.target&&anchor.target!=="_self"||anchor.hasAttribute("download"))return;
event.preventDefault();
event.stopImmediatePropagation();
location.assign(anchor.getAttribute("href"));
},true);
})();</script>`;
function injectNavPatch(file) {
const html = fs.readFileSync(file, "utf8");
if (html.includes("data-static-export-nav")) return;
const patched = html.includes("</body>")
? html.replace("</body>", `${STATIC_NAV_PATCH}</body>`)
: html + STATIC_NAV_PATCH;
fs.writeFileSync(file, patched);
}
// 2) คัดลอก asset ที่ build ไว้แล้ว (ไม่ต้องโหลดซ้ำ)
const publicDir = path.join(".output", "public");
if (fs.existsSync(publicDir)) {
fs.cpSync(publicDir, OUT, { recursive: true });
}
// 3) ลิงก์ย่อ /c/<slug> ทำเป็นหน้า redirect แบบ static
let redirects = 0;
for (const slug of uniqueSlugs) {
const dir = path.join(OUT, "c", slug);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, "index.html"),
`<!doctype html><meta charset="utf-8"><title>กำลังพาไป…</title>
<link rel="canonical" href="/cinema/${slug}">
<meta http-equiv="refresh" content="0; url=/cinema/${slug}">
<script>location.replace("/cinema/${slug}")</script>
<a href="/cinema/${slug}">ไปที่หน้าโรงหนัง</a>
`,
);
redirects++;
}
// 4) 404 fallback (static host ส่วนใหญ่ใช้ 404.html)
fs.writeFileSync(
path.join(OUT, "404.html"),
fs.readFileSync(path.join(OUT, "index.html"), "utf8"),
);
for (const file of fs.readdirSync(OUT, { recursive: true })) {
const full = path.join(OUT, String(file));
if (full.endsWith(".html")) injectNavPatch(full);
}
const files = fs.readdirSync(OUT, { recursive: true }).length;
console.log(
`export เสร็จ: ${ok}/${routes.length} หน้า · ${redirects} redirect · ${files} entries`,
);
console.log(`outDir: ${path.resolve(OUT)}`);
if (failed.length) console.log(`ล้มเหลว: ${failed.join(", ")}`);