React+Vite项目部署至GitHub Pages后路由失效页面404求助
解决React+Vite部署到gh-pages的子路径404问题
1. 配置Vite的base路径
在项目根目录的vite.config.js中添加base配置,值为你的GitHub仓库名称(gh-pages部署路径格式为用户名.github.io/仓库名/):
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], base: '/your-repo-name/', // 替换为实际仓库名称 });
2. 设置BrowserRouter的basename
修改App.jsx中的Router组件,添加basename属性匹配部署路径:
import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; function App() { return ( <Router basename="/your-repo-name/"> {/* 替换为实际仓库名称 */} <Header /> <div className="app"> <Routes> <Route path="/" element={<Home />} /> <Route path="/example" element={<Example />} /> </Routes> </div> </Router> ); }
3. 创建404.html实现路由重定向
Vite打包后生成dist目录,复制dist/index.html并重命名为dist/404.html(内容完全一致)。
接着在dist/index.html的<head>标签内添加以下脚本,处理路由跳转时的路径问题:
<script> const repoName = '/your-repo-name/'; // 替换为实际仓库名称 if (!window.location.pathname.startsWith(repoName)) { window.history.replaceState(null, null, repoName + window.location.pathname.slice(1)); } </script>
4. 确保部署脚本正确
在package.json中配置部署相关脚本:
{ "scripts": { "build": "vite build", "predeploy": "npm run build", "deploy": "gh-pages -d dist" } }
执行npm run deploy重新部署后,子路径访问和路由切换即可正常工作。
内容的提问来源于stack exchange,提问作者Yehuda
相关产品推荐
相关产品推荐

