GitLab流水线构建部署成功但React页面显示空白求助
问题:Create React App部署GitLab Pages后页面空白,%PUBLIC_URL%占位符未被替换
问题背景
本地运行正常的默认Create React App项目,已推送到关联GitLab Pages的仓库,访问地址为https://reactwebsitetobetested-alexandreasen09-9e495b734d3272d04dc8ee99.gitlab.io/。部署后页面显示空白,控制台报错提示%PUBLIC_URL%占位符未被替换,导致资源加载失败。
当前CI配置文件(.gitlab-ci.yml)
# The Docker image that will be used to build your app image: node:lts # Functions that should be executed before the build script is run before_script: - npm ci variables: GITLAB_PAGES_URL: "https://reactwebsitetobetested-alexandreasen09-9e495b734d3272d04dc8ee99.gitlab.io/" PUBLIC_URL: "$GITLAB_PAGES_URL" # Optional, define if needed pages: image: node:latest script: - npm install - npm run build --publicPath="$PUBLIC_URL" # Prepend PUBLIC_URL for asset paths - mv build public artifacts: paths: - public only: - main
控制台报错信息
/%PUBLIC_URL%/favicon.ico:1 Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR /%PUBLIC_URL%/manifest.json:1 Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR /%PUBLIC_URL%/favicon.ico:1 Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR /%PUBLIC_URL%/manifest.json:1 Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR
项目文件夹结构
reactwebsitetobetested (项目主文件夹) - README (Markdown文件) - node_modules (文件夹) - public (文件夹) -- favicon.ico -- index.html -- logo192.png -- logo512.png -- manifest.json -- robots.txt - src (文件夹) - .gitignore - package.json - package-lock.json - .gitlab-ci.yml
解决方案
1. 正确传递PUBLIC_URL环境变量
Create React App会读取PUBLIC_URL环境变量来替换index.html中的%PUBLIC_URL%占位符,需在构建时直接注入该变量,而非通过publicPath参数传递。修改CI的pages脚本:
pages: script: - npm install - PUBLIC_URL="$GITLAB_PAGES_URL" npm run build - mv build public
注意:移除GITLAB_PAGES_URL末尾的斜杠,确保变量值为https://reactwebsitetobetested-alexandreasen09-9e495b734d3272d04dc8ee99.gitlab.io,避免生成重复斜杠的资源路径。
2. 简化publicPath配置(根部署场景)
如果是GitLab Pages根域名部署(无子路径),可以直接省略publicPath参数,CRA默认会使用/作为资源根路径,此时只需确保PUBLIC_URL环境变量正确传递即可。
3. 优化CI配置(可选)
统一Node镜像版本,添加依赖缓存加速构建:
image: node:lts cache: paths: - node_modules/ before_script: - npm ci variables: GITLAB_PAGES_URL: "https://reactwebsitetobetested-alexandreasen09-9e495b734d3272d04dc8ee99.gitlab.io" pages: script: - PUBLIC_URL="$GITLAB_PAGES_URL" npm run build - mv build public artifacts: paths: - public only: - main
验证步骤
- 将修改后的
.gitlab-ci.yml推送到main分支 - 等待GitLab CI流水线执行完成
- 访问页面,检查控制台是否仍有资源加载错误,确认页面正常渲染
内容的提问来源于stack exchange,提问作者Alex09
相关产品推荐
相关产品推荐

