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

本地yarn serve仅能访问index.htm及GitLab CI流水线问题求助

问题原因及解决办法

核心原因

你遇到的问题和serve命令的-s参数直接相关:

  • -s是单页应用(SPA)模式,当请求的路径不存在对应静态文件时,会自动重定向到index.html。但如果静态文件确实存在,理论上应该正常返回,所以还要排查文件生成是否正常。
  • 本地用yarn serve(如果是react-scripts start)默认就是SPA模式,非public目录下的静态文件无法直接访问,因为开发服务器只把public目录作为静态资源根目录。

分步排查与解决

1. 确认version.html是否正确生成

在GitLab CI的build website阶段添加验证步骤,确保文件存在且内容正确:

build website:
    image: node:16-alpine
    stage: build
    script:
        - yarn install
        - yarn lint
        - yarn test
        - yarn build
        - echo $APP_VERSION > build/version.html
        - ls -la build  # 查看build目录下的所有文件
        - cat build/version.html  # 验证文件内容
    artifacts:
        paths:
            - build

2. 调整test阶段的serve命令

如果不需要SPA模式,直接去掉-s参数,用静态文件服务器模式:

test index:
    image: node:16-alpine
    stage: test
    script:
        - yarn global add serve
        - apk add curl
        - serve build &  # 去掉-s参数
        - sleep 5  # 可适当缩短sleep时间,确认服务启动即可
        - curl http://localhost:3000 | grep 'React App'
        - curl http://localhost:3000/$VERSION_PATH | grep $APP_VERSION

如果必须保留SPA模式(比如你的应用是单页应用),要确保version.html确实在build根目录下,此时serve -s会优先返回存在的静态文件,只有文件不存在时才重定向到index.html。如果还是访问不到,可改用更可靠的方式等待服务启动:

test index:
    image: node:16-alpine
    stage: test
    script:
        - yarn global add serve
        - apk add curl
        - serve -s build &
        # 循环等待服务启动,最多尝试10次
        - for i in {1..10}; do
            curl -s http://localhost:3000 > /dev/null && break;
            sleep 1;
          done
        - curl http://localhost:3000 | grep 'React App'
        - curl http://localhost:3000/$VERSION_PATH | grep $APP_VERSION

3. 本地问题解决

如果本地用的是react-scripts start(即yarn start),要访问静态文件需要把文件放在项目根目录的public文件夹下;如果是用全局serve命令启动本地服务,去掉-s参数,直接启动静态服务器即可访问build目录下的所有文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:28:12