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

无法通过GitHub Action将React应用正确部署至Firebase Hosting

React应用GitHub Action部署Firebase出现404错误的解决方案

问题概述

本地执行firebase deploy --only hosting可成功部署React应用,访问[my-domain]/sub-dir/build正常;但通过GitHub Action部署后,同一URL返回404错误页。

项目目录结构

- github
  - workflow
    - action.yaml
- public
  - sub-dir(React App)
    - build

原Action配置的核心问题

  1. 重复Checkout覆盖构建产物:先使用actions/checkout@v3拉取代码,后续又执行actions/checkout@master,导致之前构建好的build文件夹被重置覆盖。
  2. 冗余Git操作干扰流程:构建后执行git add/commit/push,又在部署前git pull,这些操作完全没必要,反而会破坏构建后的文件状态。
  3. 步骤顺序混乱:部署相关步骤(安装firebase-tools)被放在冗余操作之后,且依赖安装逻辑混乱,导致部署时无法正确识别构建产物。

修复后的GitHub Action配置

name: Continuous Deployment

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-20.04
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: "14.18.3"
          cache: "yarn"

      # 构建React子项目
      - name: Build React application
        run: |
          cd public/sub-dir
          yarn install --frozen-lockfile
          yarn build

      # 部署到Firebase Hosting
      - name: Install Firebase Tools
        run: npm install -g firebase-tools

      - name: Deploy to Firebase
        run: firebase deploy --only hosting
        env:
          FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}

关键修改说明

  • 移除冗余操作:删除重复Checkout、Git配置及推送拉取步骤,避免破坏构建产物。
  • 优化步骤顺序:先拉取代码→配置Node环境→构建React项目→安装Firebase工具→部署,确保部署时build目录存在且未被修改。
  • 缓存依赖:指定cache: "yarn"匹配子项目的包管理工具,提升构建效率。

额外配置检查

确保firebase.json的Hosting配置指向正确的构建目录,否则Firebase无法找到静态文件:

{
  "hosting": {
    "public": "public/sub-dir/build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}
  • public字段:明确指定React构建产物的路径。
  • rewrites配置:处理React单页应用的路由刷新问题,避免后续页面跳转出现404。

验证方法

  1. 将修改后的action.yaml提交到main分支,触发GitHub Action运行。
  2. 查看Action日志,确认Build React application和Deploy to Firebase步骤无报错。
  3. 部署完成后访问目标URL,验证页面正常加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:36:58