部署网站
概述
使用此技能指导将已生成的网站部署到 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
在需要时简单解释这些 Actions:
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 失败:仓库或权限问题。
- Install/build 失败:依赖、Astro 或源代码问题。
- Deploy 失败:GitHub Pages 源/权限/设置问题。
完成标准
满足以下条件时,视为部署任务完成:
- 本地构建通过。
- 源代码更改已提交并推送。
- GitHub Pages 源已设置为 GitHub Actions。
- Actions 部署运行成功。
- 公共 Pages URL 正确加载网站。