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

+2
View File
@@ -41,3 +41,5 @@ learnings.md
.vercel/
.agent-native/
data/*.lock
# static export (artifact)
static-export/
+20
View File
@@ -94,6 +94,26 @@ AGENTS.md กฎสำหรับ agent/AI ที่แก้โค้
| `ANALYTICS_SALT` | แนะนำ | เกลือ hash ผู้เข้าชม (กันคาดเดา) |
| `SITE_URL` / `SHARE_ORIGIN` | ไม่ต้อง | บังคับโดเมนเฉพาะกรณี (ปกติปล่อยว่าง) |
## Static export (โฮสต์แบบไฟล์นิ่ง / มี `index.html`)
แอปนี้เป็น SSR + หลังบ้านเขียนไฟล์ได้ → ค่าปกติต้องรันเป็น Node server (`node .output/server/index.mjs`)
ถ้าต้องการ **ไฟล์นิ่งที่มี `index.html`** ใช้สคริปต์ export (ดึง HTML ทุกหน้าจากตัว server ที่รันอยู่):
```bash
pnpm build # ได้ .output (preset node)
PORT=8090 node .output/server/index.mjs # เปิด server ตัวจริง
pnpm export:static http://127.0.0.1:8090 static-export
python -m http.server 8091 --directory static-export # ทดสอบแบบ static
```
ผลลัพธ์: `static-export/index.html`, `about/index.html`, `cinema/<slug>/index.html` (ทุกโรงที่ไม่ `hidden`), `c/<slug>/index.html` (redirect), `sitemap.xml`, `robots.txt`, `assets/`, `images/`, `404.html`
**ข้อจำกัดที่ตั้งใจ (static ไม่มี backend)**
- ไม่มี `/admin` และ `/api/*` — ต้องใช้ Node server ถ้าจะแก้เนื้อห ผมเพิ่ม/แก้ผ่านหลังบ้าน
- ไม่มี `?_data=` ของ React Router → สคริปต์ inject ตัวดักคลิก (`data-static-export-nav`) ให้ทุก link เป็นการโหลดหน้าเต็ม (ทุกหน้ามี HTML ของตัวเอง) — คลิก/ย้อนกลับ/รีเฟรชทำงานปกติ แต่ไม่มีการเปลี่ยนหน้าแบบ SPA
- ลิงก์แชร์ `/c/<slug>` กลายเป็นหน้า `meta refresh` + JS redirect (ไม่ใช่ 302 ของ server)
- canonical/OG ถูกอบตอน export — ตั้ง `SITE_URL` ตอนรัน server ก่อน export ถ้าต้องการโดเมนจริงใน meta
## เอกสารอื่น
- [DESIGN.md](DESIGN.md) — สัญญาการออกแบบ: พาเลตต์ ฟอนต์ โลโก้ layout motion PWA SEO และกติกากันข้อมูลหาย
+1
View File
@@ -8,6 +8,7 @@
"migrate:production": "tsx scripts/migrate-production.ts && pnpm db:migrate",
"dev": "agent-native dev",
"build": "agent-native build",
"export:static": "node scripts/static-export.mjs",
"start": "agent-native start",
"typecheck": "agent-native typecheck",
"action": "agent-native action",
+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(", ")}`);