您可以查看文档 https://create-react-app.dev/docs/deployment from create-react-app
关于这一点。
将主页添加到 package.json .
打开 package.json 并为您的项目添加主页字段:
"homepage": "https://myusername.github.io/my-app",
或者对于 GitHub 用户页面:
"homepage": "https://myusername.github.io",
Create React App 使用主页字段来确定构建的 HTML 文件中的根 URL。
安装 gh-pages 并将部署添加到 package.json 中的脚本中
现在,每当您运行 npm run build 时,您都会看到一份备忘单,其中包含有关如何部署到 GitHub Pages 的说明。
发布于https://myusername.github.io/my-app https://myusername.github.io/my-app, run:
npm install --save gh-pages
或者你可以使用纱线:
纱线添加 gh-pages
在 package.json 中添加以下脚本:
"scripts": {
+ "predeploy": "npm run build",
+ "deploy": "gh-pages -d build",
"start": "react-scripts start",
"build": "react-scripts build",
预部署脚本将在部署运行之前自动运行。
如果您要部署到 GitHub 用户页面而不是项目页面,则需要进行两项额外的修改:
首先,将存储库的源分支更改为除 master 之外的任何分支。
此外,调整您的 package.json 脚本以将部署推送到 master:
"scripts": {
"predeploy": "npm run build",
- "deploy": "gh-pages -d build",
+ "deploy": "gh-pages -b master -d build",
通过运行 npm run deploy 来部署站点
然后运行:
npm run deploy
第 4 步:确保项目的设置使用 gh-pages
最后,确保 GitHub 项目设置中的 GitHub Pages 选项设置为使用 gh-pages 分支: