Vite构建React应用部署GitHub Pages后路由缺失仓库名问题
解决Vite React应用部署GitHub Pages后路由不包含仓库名的问题
问题核心是React Router的BrowserRouter默认以域名根路径(/)作为路由基准,没适配GitHub Pages的子路径(/imagerfe/),导致跳转时丢失仓库名前缀。
具体修复步骤:
给BrowserRouter添加basename属性
在app.jsx中修改BrowserRouter组件,指定basename为你的仓库名,所有路由会自动带上该前缀:修改后的
app.jsx代码:import { BrowserRouter, Link, Route, Routes } from "react-router-dom"; import { logo } from "./assets"; import { Home, CreatePost } from "./pages"; const App = () => { return ( <BrowserRouter basename="/imagerfe/"> <header className="w-full flex justify-between items-center bg-white sm:px-8 px-4 py-4 border-b border-b-[#e6ebf4]"> <Link to="/"> <img src={logo} alt="logo" className="w-28 object-contain" /> </Link> <Link to="/create-post" className="font-inter font-medium bg-[#6469ff] text-white px-4 py-2 rounded-md" > Create </Link> </header> <main className="sm:p-8 px-4 py-8 w-full bg-[#f9fafe] min-h-[calc(100vh-73px)]"> <Routes> <Route path="/" element={<Home />} /> <Route path="/create-post" element={<CreatePost />} /> </Routes> </main> </BrowserRouter> ); }; export default App;确认Vite配置无需修改
你的vite.config.js中已设置base: "/imagerfe/",该配置能确保构建后的静态资源路径自动带上仓库名前缀,保持当前状态即可。重新构建部署
执行以下命令更新部署:npm run build npm run deploy
验证效果
部署完成后,点击logo或Create按钮,路由会自动跳转到https://tehcatsmiaw.github.io/imagerfe/和https://tehcatsmiaw.github.io/imagerfe/create-post,不再丢失仓库名前缀。
内容的提问来源于stack exchange,提问作者tehcatsmiaw
相关产品推荐
相关产品推荐

