用Cloudflare Pages 部署 Astro 專案的完整流程,從建立專案到綁定 GitHub 自動部署。
步驟一:準備 Astro 專案
先確認你的專案可以正常建置。
npm installnpm run build如果成功,專案根目錄會出現:
dist/這就是 Cloudflare 要部署的資料夾。
步驟二:將專案推送到 GitHub
如果還沒建立 Git Repository:
git initgit add .git commit -m "Initial commit"到 GitHub 建立新的 Repository,例如:
astro-blog然後推送:
git remote add origin https://github.com/你的帳號/astro-blog.gitgit branch -M maingit push -u origin main步驟三:建立 Cloudflare 帳號
前往: Cloudflare Dashboard 登入或註冊帳號。
步驟四:建立 Pages 專案
在 Dashboard 中:
- 點 Workers & Pages
- 點 Create
- 選 Pages
- 選 Connect to Git 第一次使用會要求授權 GitHub。
步驟五:授權 GitHub
Cloudflare 會跳到 GitHub。 建議:
Only select repositories只授權需要部署的 Repository。 例如:
astro-blog完成後返回 Cloudflare。
步驟六:選擇 Repository
Cloudflare 會列出:
astro-blog點擊:
Begin setup步驟七:設定 Build
如果是一般 Astro 專案,設定如下: Framework preset
Astro若沒有,可選:
None並手動設定。
Build command
如果使用 npm:
npm run buildBuild output directory
填入:
distRoot directory
一般保持空白:
/只有當 Astro 專案位於 Monorepo 子目錄時,才需填入相對路徑,例如 apps/web。
Environment Variables
若沒有使用環境變數,可先留空。 若有:
API_URL=https://example.comPUBLIC_SITE=https://xxx.pages.dev可於:
Settings→ Variables新增。
步驟八:開始部署
按:
Save and DeployCloudflare 會開始:
Installing dependencies
↓
Running npm run build
↓
Uploading dist
↓
Deploying首次部署通常需 1~3 分鐘。
步驟九:取得網址
完成後會得到:
https://astro-blog.pages.dev之後每次:
git pushCloudflare 都會:
- 自動拉取程式碼
- 自動建置
- 自動部署 無需手動上傳。
步驟十:查看部署紀錄
在 Pages 專案中可以查看:
Deployments包含:
- 每次部署時間
- Commit
- Build Log
- 是否成功 若建置失敗,可點進該次部署查看完整日誌。
自訂網域(可選)
若有自己的網域: 例如:
example.com在專案:
Custom Domains點:
Set up a custom domain輸入:
www.example.comCloudflare 會自動設定 DNS(若網域已使用 Cloudflare 管理),並簽發免費 SSL 憑證。
Astro SSR(可選)
如果你的專案需要 SSR(Server-Side Rendering),先安裝 Cloudflare Adapter:
npm install @astrojs/cloudflare修改 astro.config.mjs:
import { defineConfig } from "astro/config";import cloudflare from "@astrojs/cloudflare";
export default defineConfig({ output: "server", adapter: cloudflare(),});之後重新推送即可部署 SSR 應用。
常見問題
找不到 Astro Framework?
可直接使用以下設定: 項目 值 Build Command npm run build Output Directory dist
Build Failed?
常見原因包括:
- Node.js 版本不相容
- package.json 缺少必要的相依套件
- npm run build 在本機無法成功執行
- 環境變數未設定 建議先在本機執行:
npm run build確認能成功完成,再推送到 GitHub。
