部署網站
總覽
使用此技能引導將已產生的網站部署到 GitHub Pages。預期的專案是儲存在 GitHub 儲存庫中的 Astro 靜態網站,原始檔已提交,並由 GitHub Actions 處理部署。
此技能假設網站本身已經存在。請勿重新設計網站,除非使用者要求。
部署模型
使用此設定作為目前個人網站工作流程:
- 在 Git 中追蹤原始碼。
- 忽略產生或依賴性資料夾,例如
node_modules/、dist/、.astro/和tmp/。 - 使用
npm.cmd run build建置網站。 - 透過 GitHub Actions 部署到 GitHub Pages。
- 本機開發在
http://localhost:4321/進行。 - 僅在 GitHub Actions 建置時使用 Astro
base路徑,以符合專案 Pages URL,例如https://USERNAME.github.io/REPOSITORY/。
部署前
使用輕量指令檢查準備狀態:
git status
npm.cmd run build
確認存在這些檔案或設定:
package.jsonastro.config.mjs.gitignore.github/workflows/deploy.ymlsrc/public/
對於此專案,astro.config.mjs 應支援本機開發和 GitHub Pages 建置,例如:
import { defineConfig } from "astro/config";
const isGithubPagesBuild = process.env.GITHUB_ACTIONS === "true";
export default defineConfig({
site: "https://USERNAME.github.io",
base: isGithubPagesBuild ? "/REPOSITORY" : "/",
});
在 Astro 頁面/佈局中連結到本機公共資源或內部頁面時,使用 URL 輔助函數:
const base = import.meta.env.BASE_URL;
const url = (path: string) => {
const normalizedBase = base.endsWith("/") ? base : `${base}/`;
const normalizedPath = path.replace(/^\/+/, "");
return `${normalizedBase}${normalizedPath}`;
};
GitHub Actions 工作流程
使用類似這樣的 Pages 工作流程:
name: Deploy to GitHub Pages
on:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: false
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v7
- name: Build with Astro
uses: withastro/action@v6
deploy:
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v5
必要時簡單解釋這些 Action:
actions/checkout@v7:將儲存庫下載到 GitHub Actions 執行器中。withastro/action@v6:安裝依賴項、建置 Astro 網站並準備 Pages 成品。actions/deploy-pages@v5:將建置好的成品發佈到 GitHub Pages。
@vN 後綴會鎖定 Action 的主要版本。
儲存庫與提交步驟
引導使用者提交並推送部署就緒的原始碼變更:
git status
git add .
git commit -m "準備網站部署"
git push origin main
如果 Git 報告換行符號警告,例如 LF will be replaced by CRLF,請解釋這是 Windows 行尾正規化警告,通常不會阻礙部署。
如果 Git 報告未設定使用者身分,請在提交前設定儲存庫或全域身分。如果在意隱私,請使用使用者的 GitHub noreply 電子郵件。
GitHub Pages 設定
引導使用者在 GitHub 中操作:
- 在 GitHub 上開啟儲存庫。
- 前往
Settings。 - 前往
Pages。 - 在
Build and deployment下,將Source設定為GitHub Actions。 - 如果 GitHub 顯示儲存按鈕,請點擊儲存。
- 前往
Actions標籤頁,開啟最新的部署執行。 - 等待工作流程成功。
- 開啟 GitHub 顯示的 Pages URL。
對於專案網站,預期的 URL 通常是:
https://USERNAME.github.io/REPOSITORY/
驗證
部署後,確認:
- 首頁可載入。
- 導覽連結可運作。
- 圖片可載入。
- 可下載的檔案,例如 CV PDF,能正確開啟。
- 瀏覽器 URL 包含專案 Pages 的儲存庫路徑。
- 產生的 HTML 中沒有出現類似
/REPOSITORYprojects、/REPOSITORYprofile.jpg或/REPOSITORYfile.pdf的錯誤路徑。
如果已部署的網站出現問題但本機預覽正常,請先檢查 base 路徑的處理方式。
如果 GitHub Actions 失敗,請檢查失敗的步驟:
- Checkout 失敗:儲存庫或權限問題。
- 安裝/建置失敗:依賴項、Astro 或原始碼問題。
- 部署失敗:GitHub Pages 來源/權限/設定問題。
完成條件
當滿足以下條件時,部署任務視為完成:
- 本機建置通過。
- 原始碼變更已提交並推送。
- GitHub Pages 來源已設定為 GitHub Actions。
- Actions 部署執行成功。
- 公共 Pages URL 正確載入網站。