You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Vite+GitHub Actions部署至GitHub Pages出现404空白页求助

解决Vite项目部署GitHub Pages后空白+404问题

以下是针对你问题的分步排查和解决方法:

1. 确保Vite的base配置完全正确

GitHub Pages的资源路径规则是:

  • 如果是个人/组织主页(如xxx.github.io),base设为'/'
  • 如果是项目仓库(如xxx.github.io/my-vite-project),base必须设为'/my-vite-project/'(注意前后斜杠不能少)

修改vite.config.ts:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  base: '/你的仓库名称/' // 替换为实际仓库名,比如 '/vite-gh-pages-demo/'
})

也可以通过打包命令动态指定,避免影响本地开发:

vite build --base=/你的仓库名称/

2. 修正GitHub Actions部署脚本

确保部署脚本正确指向Vite的打包目录(默认是dist),同时禁用Jekyll避免文件被忽略:

创建/修改.github/workflows/deploy.yml:

name: Deploy to GitHub Pages

on:
  push:
    branches: [main] # 替换为你的主分支名(如master)

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'

      - name: Install dependencies
        run: npm install

      - name: Build project
        run: npm run build # 确保package.json的build命令是"vite build"

      - name: Deploy to Pages
        uses: peaceiris/actions-gh-pages@v4
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./dist
          publish_branch: gh-pages
          jekyll: false # 禁用Jekyll,防止静态资源被过滤

同时要去仓库的Settings > Pages里,确认部署源是gh-pages分支的/root目录。

3. 处理SPA路由导致的刷新404

如果你的项目是单页应用(用了React Router等客户端路由),直接部署会出现刷新页面404的问题,需要添加404.html文件:

修改package.json的build命令,打包后自动复制index.html为404.html:

"scripts": {
  "dev": "vite",
  "build": "vite build && cp dist/index.html dist/404.html", // Linux/macOS
  // Windows环境用这条:"build": "vite build && copy dist\\index.html dist\\404.html",
  "preview": "vite preview"
}

4. 检查资源引用路径

打包后打开dist/index.html,确认所有资源(JS/CSS/图片)的引用路径是/仓库名/assets/xxx格式,而不是绝对路径/assets/xxx。

另外,不要手动修改main.tsx的导入路径,保持Vite默认的模块导入方式即可(比如import App from './App')。

5. 验证部署结果

  • 访问GitHub Pages地址时,确保末尾带斜杠(如https://xxx.github.io/my-vite-project/)
  • 查看gh-pages分支的内容,确认dist下的所有文件都已上传

内容的提问来源于stack exchange,提问作者Oscar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:13:03