部署你的 Astro 站点至 GitHub Pages
您可以使用 GitHub Pages 直接从 GitHub 上的存储库托管 Astro 网站。
如何部署
标题部分 如何部署你可以使用 GitHub Actions 将 Astro 站点自动构建和部署到 GitHub Pages。为此,你的源代码必须托管在 GitHub 上。
Astro 维护了一个官方的 GitHub Action withastro/action
来帮助你部署项目;你只需很少的配置,就可以完成部署。按照下面的说明可以将你的 Astro 站点部署到 GitHub Pages,如果你需要更多信息,请参阅这个包的 README。
-
在配置文件设置
site
,并在astro.config.mjs
中根据需要设置base
选项。astro.config.mjs import { defineConfig } from 'astro/config'export default defineConfig({site: 'https://astronaut.github.io',base: '/my-repo',})site
应当为https://<YOUR_USERNAME>.github.io
或https://my-custom-domain.com
base
应当是你的存储库的名称,以正斜杠(/
)开头, 例如/my-repo
。这是为了告诉 Astro 你的网站的根目录是/my-repo
,而非默认的/
。
-
在你的项目中的
.github/workflows/
目录创建一个新文件deploy.yml
,并粘贴以下 YAML 配置信息。deploy.yml name: Deploy to GitHub Pageson:# 每次推送到 `main` 分支时触发这个“工作流程”# 如果你使用了别的分支名,请按需将 `main` 替换成你的分支名push:branches: [ main ]# 允许你在 GitHub 上的 Actions 标签中手动触发此“工作流程”workflow_dispatch:# 允许 job 克隆 repo 并创建一个 page deploymentpermissions:contents: readpages: writeid-token: writejobs:build:runs-on: ubuntu-lateststeps:- name: Checkout your repository using gituses: actions/checkout@v3- name: Install, build, and upload your siteuses: withastro/action@v0# with:# path: . # 存储库中 Astro 项目的根位置。(可选)# node-version: 16 # 用于构建站点的特定 Node.js 版本,默认为 16。(可选)# package-manager: yarn # 应使用哪个 Node.js 包管理器来安装依赖项和构建站点。会根据存储库中的 lockfile 自动检测。(可选)deploy:needs: buildruns-on: ubuntu-latestenvironment:name: github-pagesurl: ${{ steps.deployment.outputs.page_url }}steps:- name: Deploy to GitHub Pagesid: deploymentuses: actions/deploy-pages@v1 -
在 GitHub 上,跳转到存储库的 Settings 选项卡并找到设置的 Pages 部分。
-
选择 GitHub Actions 作为你网站的 Source,然后按 Save。
-
提交(commit)这个新的“工作流程文件”(workflow file)并将其推送到 GitHub。
您的网站现在应该已完成发布了!当你将更改推送到 Astro 项目的存储库时,GitHub Action 将自动为你部署它们。