2024.4.26亲测 😀
步骤
- 首先创建新仓库
建议命名为
你的github名字.github.io
这样后面就不会产生路径问题
详细原因可见React/Vue 项目在 GitHub Pages上部署时资源的路径问题,很详细
- 把本地代码传到git
在项目根目录执行
git init
git add .
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/Li-kuaile/blog.git
git push -u origin main
- 配置本地文件里的package.json
- 添加一项
"homepage": "./",
- 在scripts下添加
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
注意deploy里的命令对应的目录不一定都是build(我用vite就是dist
配置上后大概就是这样
- 安装gh-pages,并再次提交
- 安装命令
npm install gh-pages --save-dev
- 提交命令
git add .
git commit -m "deploy commit"
git push
- 构建
- 运行命令
npm run deploy
- 去github页面
按如下步骤操作
注意,这里可能第四步的链接出现需要等待一段时间
如果报错可以去actions页面看报错原因
可能的问题
- Error: Liquid syntax error
github pages默认会通过Jekyll构建页面,而Jekyll使用Liquid 处理所有输入文件中的所有 {{ 和 {% 组合,导致我的页面里要渲染的md文件会因为括号问题报错(果然免费的就是最贵的)
- 解决办法就是在有括号问题的地方,前后加上加 Liquid raw tag,也就是{% raw %},{% endraw %}
解决办法
在 GitHub Pages 中呈现任意 LaTeX
源码片段 如何修复 React 代码片段中的 Liquid语法错误
- Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “text/html”. Strict MIME type
这还是一个vite的路径问题,在vite.config.js
文件里加上这一项就行
- No url found for submodule path ‘node_modules/.cache/gh-pages/https!github.com!Li-kuaile!Li-kuaile.github.io.git’ in .gitmodules
The process ‘/usr/bin/git’ failed with exit code 128
- build失败,github action里提示报错信息
- 解决办法
git rm --cache 报错的路径
4.> gh-pages -d dist Error: Failed to get remote.origin.url
更新了几版后重新部署到ghpage,结果报这个错误。网上给出的建议都是检查是否设置正确git仓库,但对我解决无果。
最终删除github上ghpage分支+删除node_modules.cache\gh-pages文件夹,更新git,然后重新npm run deploy,最后成功
注意
如果你使用了BrowserRouter,github pages可能会出现刷新后404
- 可以在dist路径下添加一个404.html文件,内容和index.html一样。
- 或者改成HashRouter
!!!!!可能的问题2可参考!!!!!!!!!!!!!!!
使用vite构建react的小伙伴可以看看这个,如果你构建的项目在https://<USERNAME>.github.io/<REPO>/
上,则需要在vite.config.js 中设置正确的 base
,否则路径就不对
export default defineConfig({
plugins: [react()],
base:'/<REPO>/'
});
https://vitejs.cn/vite3-cn/guide/static-deploy.html#building-the-app
不得不说
真是坎坷,本地都写好了,放到github上结果一直报错😡