教學 · 部署 · ★★★☆☆
用 Claude Code 把 Angular 部署到 Cloudflare
這個網站是怎麼上線的:每個頁面都預先渲染成靜態 HTML,由 Cloudflare 提供,並加上嚴格的內容安全政策(CSP)。還有那次壞掉的建置,以及修好它的那一個檔案。
作者 Arthur Hsiao · 最後更新 · 閱讀時間 4 分鐘
計畫。 教學網站不需要伺服器。Angular 在建置時把每個路由渲染成 HTML,Cloudflare 負責提供這些檔案。 每次請求都不會執行伺服器程式碼,所以沒有東西需要擴充,也幾乎沒有東西可以攻擊。
1預先渲染每個路由
這個專案建立時開了 SSR,所以 angular.json 裡是 outputMode: "server"。接著用一條規則,把每個路由都變成靜態 HTML:
// src/app/app.routes.server.ts
export const serverRoutes: ServerRoute[] = [
{ path: '**', renderMode: RenderMode.Prerender },
];執行 ng build 後,dist/ahdevstudio/browser 裡每個路由都有一個 index.html。這個資料夾就是整個網站。
2讓瀏覽器專用的程式碼遠離建置
預先渲染會在 Node 裡執行你的元件,而 Node 沒有 window、document 或 localStorage。
任何用到它們的程式碼都只能在瀏覽器裡執行,例如放在 afterNextRender 裡。我把這條規則寫進專案的 CLAUDE.md,讓 Claude 每次對話都遵守:
Any code touching window/document/localStorage must run browser-only (afterNextRender, or guarded), or the prerender breaks.
更多關於這個檔案的寫法:CLAUDE.md 最佳做法。
3把 Cloudflare 的檔案放進 public/
Angular 會把 public/ 原封不動複製到建置結果裡,所以 Cloudflare 的設定檔放在那裡:
_headers:安全性標頭,以及字型的長期快取。_redirects:舊網址的轉址,例如/guide.html /guide 301。404.html:任何不存在的路徑都會顯示它。
4壞掉的建置
我在 Cloudflare 後台連接了 repo,執行 npx wrangler deploy。Wrangler 看到一個有 SSR 設定的 Angular 專案,
就把它設定成伺服器應用程式,結果建置失敗。這個網站從來不需要伺服器,但沒有任何東西告訴 Wrangler 這件事。
修法是在 repo 根目錄放一個 wrangler.jsonc,告訴它「這些是靜態檔案,直接提供就好」:
// wrangler.jsonc: a Worker that only serves the prerendered site (no server code runs).
{
"name": "ahdevstudio",
"compatibility_date": "2026-10-23",
"assets": {
"directory": "./dist/ahdevstudio/browser",
"not_found_handling": "404-page"
}
}not_found_handling: "404-page" 讓 Cloudflare 用真正的 404 狀態碼提供 404.html。push 之前先檢查:
npm run build npx wrangler deploy --dry-run # lists the files it would upload, deploys nothing
5後台設定一次就好
| 設定 | 值 |
|---|---|
| 建置指令 | npm run build |
| 部署指令 | npx wrangler deploy |
| 正式環境分支 | main |
Angular 22 需要較新的 Node,所以用一個內容是 22.22.3 的 .node-version 檔案,替 Cloudflare 的建置固定版本。
6建置後加上嚴格的 CSP
Angular 的 autoCsp 選項無法和預先渲染一起使用。所以 npm run build 會先執行 ng build,再執行一個小腳本,
把建置出來的 HTML 裡每個內嵌腳本做雜湊,然後把政策寫進建置結果的 _headers:
// scripts/csp.mjs (runs after ng build)
for (const page of html) {
for (const [, attrs, body] of page.matchAll(/<script([^>]*)>([\s\S]*?)<\/script>/g)) {
if (/\bsrc=/.test(attrs) || !body.trim()) continue; // external or empty: not inline code
hashes.add(`'sha256-${createHash('sha256').update(body).digest('base64')}'`);
}
}因為每次建置都會重新計算雜湊,修改內嵌腳本不會弄壞網站。只有新的外部來源需要手動加進腳本。
一定要用真正的建置指令檢查。 單純的 ng build 會跳過 CSP 步驟,所以一個頁面可能在本機正常,到了正式環境卻被擋下。
每次 commit 之前,我都請 Claude 執行 npm run build,而不是 ng build。
下一步:在同一個網站加上捲動動畫,又不弄壞預先渲染:在 Angular 使用 GSAP 捲動動畫。
需要一個像 you@yourdomain.com 這樣的網站信箱?請看用 Cloudflare 和 Gmail 免費設定自訂網域信箱。
push 到 main 就會部署網站,所以 commit 和 push 都要有意識地做:給 Claude Code 新手的 Git 教學。