You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TanStack Router+GitHub Pages的SPA直接访问路由报404求助

解决TanStack Router + GitHub Pages 子路由直接访问404问题

方案一:使用哈希路由模式

TanStack Router支持哈希路由,只需修改路由创建逻辑切换到hash history:

  1. 在你的Router.ts中导入createHashHistory:
import { createRouter, createHashHistory } from '@tanstack/react-router'
  1. 创建哈希历史实例并传入路由配置:
const history = createHashHistory({ window })

const router = createRouter({
  history,
  basePath: '/beyond-brand-boosters/', // 匹配你的GitHub Pages项目路径
  routes: [
    // 你的现有路由配置
  ],
})

部署后路由会变为https://jbetoreyes.github.io/beyond-brand-boosters/#/about-us形式,直接访问该URL时,服务器会加载根目录的index.html,TanStack Router解析哈希部分的路由即可避免404。

方案二:配置404页面 fallback(无哈希URL)

若想保持干净的URL结构,可通过GitHub Pages的404页面机制让所有子路由请求返回index.html:

  1. 在项目public目录下,复制index.html并重命名为404.html
  2. 在Router.ts中配置正确的basePath:
import { createRouter } from '@tanstack/react-router'

const router = createRouter({
  basePath: '/beyond-brand-boosters/',
  routes: [
    // 你的现有路由配置
  ],
})

部署后直接访问子路由时,GitHub Pages会返回与index.html内容一致的404.html,TanStack Router会接管路由并渲染对应页面。

注意:使用该方案时,建议在路由配置中添加通配符路由(如*),处理客户端侧未匹配的路径。

内容的提问来源于stack exchange,提问作者Jose Alberto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 06:15:00