Skip to content

初始化

创建 .github/workflows/deploy.yml

yml
# action 的名称
name: Auto Build And Deploy

# 需要开启写权限,实现打包后的文件放在到需要部署的那个分支上
permissions:
  contents: write

on:
  push:
    branches:
      # 触发的分支
      - master
      # 这里可以继续添加其他分支
      # - develop

jobs:
  build-and-deploy:
    # 服务器环境:最新版 ubuntu
    runs-on: ubuntu-latest

    steps:
      # 拉取代码
      - name: Checkout
        uses: actions/checkout@v4
        with:
          # 不让 action 记住凭证,如果第三方 action 有漏洞,泄露了凭证,也不会对仓库造成影响
          persist-credentials: false

      # 安装 nodejs
      - name: Use Node.js 22
        uses: actions/setup-node@v4
        with:
          node-version: 22.16.0 

      # 安装依赖
      - name: Install npm
        run: npm install 

      # 打包项目
      - name: Build
        run: npm run build

      # 部署到 GitHub Pages
      - name: Deploy
        # 使用别人写好的 action
        uses: peaceiris/actions-gh-pages@v4
        with:
          # 打包后的文件部署到哪个分支上,如果想部署到多个分支,就需要写多个 yml
          publish_branch: github-action
          # 打包后的文件目录
          publish_dir: dist
          # 会自动获取
          github_token: ${{ secrets.GITHUB_TOKEN }}

提交代码

在提交代码后,会自动打包,将打包后的资源放在 docs 分支中,同时需要将仓库设置为公开,私有仓库使用 action 需要付费,然后将 settings -> pages 中 Build and deployment 的 source 选择 deploy from a branch,分支选择 github-action,文件夹选择 /(root),在部署完成后通过 https://xnorain001.github.io/${仓库名} 访问,同时 vite.config.js 中的 base 字段需要配置为 /${仓库名},否则访问静态资源会出现 404

js
export default defineConfig({
  base: '/foo'
})