GitHub Actions部署React应用至gh-pages的Base路径配置问题
解决React应用部署到GitHub Pages的资源路径问题
问题核心是React构建时未指定正确的基础路径,导致资源引用默认指向根域名,而非仓库子路径。以下是具体解决步骤:
1. 配置React项目的基础路径
根据你的React项目类型,选择对应配置方式:
- Vite项目:修改
vite.config.js,添加base字段:import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], base: '/Ultimate-React-23/' // 填写你的仓库名称 }) - Create React App项目:
方式一:在package.json中添加homepage字段:
方式二:在构建命令中指定{ "homepage": "https://3gwebtrain.github.io/Ultimate-React-23/" }PUBLIC_URL环境变量(可直接在workflow中设置)
2. 更新GitHub Actions Workflow
如果使用Create React App且不想修改package.json,可以在Build步骤中注入环境变量,确保构建时使用正确路径:
name: React Build on: push: branches: ['main'] env: CI: false jobs: build: runs-on: ubuntu-latest environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} permissions: contents: 'read' id-token: 'write' pages: 'write' actions: 'write' checks: 'write' deployments: 'write' strategy: matrix: node-version: [18.x] steps: - uses: actions/checkout@v3 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v3 with: node-version: ${{ matrix.node-version }} - name: Build run: | npm install # 针对Create React App,设置PUBLIC_URL为仓库子路径 PUBLIC_URL=/Ultimate-React-23/ npm run build - name: Setup Pages uses: actions/configure-pages@v2 - name: Upload artifact uses: actions/upload-pages-artifact@v1 with: path: 'dist/' - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
原理说明
设置base(Vite)或homepage/PUBLIC_URL(Create React App)后,React构建工具会将所有资源的引用路径前缀改为指定的仓库子路径,部署后资源会从https://3gwebtrain.github.io/Ultimate-React-23/下加载,而非根域名,从而解决页面空白问题。
内容的提问来源于stack exchange,提问作者3gwebtrain
相关产品推荐
相关产品推荐

