将vitepress项目部署在github pages

297 阅读1分钟

1.设置正确的 base 路径

.vitepress/config.mts 中明确配置 base(必须与github仓库名匹配):

export default defineConfig({
  base: '/repositoryname/', // 仓库名
  build: {
    outDir: 'docs/.vitepress/dist'   //构建产物输出目录
  },
})

如果仓库名为yourname.github.io,设置base:'/'

2.连接git仓库并上传项目文件,无需打包

git init

git config --local user.email useremail  #设置用户邮箱
git config --local user.name username   #设置用户名

##本地仓库连接远程
git remote add origin git@github.com:username/repositoryname.git
#设置了多ssh时,设置别名url
git remote set-url origin git@common:username/repositoryname.git

git add .
git commit -m "初始化"
git push -u origin main

3.配置deploy.yml实现自动部署

# .github/workflows/pages.yml
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: true

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: 20    #node版本

      - name: Install dependencies
        run: npm install

      - name: Build with VitePress
        run: npm run docs:build   #根据package.json的scripts对象修改

      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: docs/.vitepress/dist   #构建输出目录

  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    needs: build
    runs-on: windows-latest
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4

4.github pages配置

在github仓库设置中,点击pages,选择main/docssave

image.png

5.等待自动部署

部署完成后可以在github仓库首页看到以下页面

image.png

访问yourname.github.io/your-repo