TanStack Router
现代化且可扩展的 React 应用路由解决方案。
ReactLynx 支持 Memory Routing 和 File-Based Routing,
其中 Memory Routing 是必需的,因为 Lynx 中存在浏览器 History API 限制,
而 File-Based Routing 通过 Rspeedy 无缝集成 @tanstack/router-plugin/rspack 来启用。
安装依赖
安装 dependencies:
安装 devDependencies:
项目配置
- File-based Routing: 通过
@tanstack/router-plugin/rspack实现。 - React 18 API 兼容性: 使用
@lynx-js/react/compat确保第三方库正常工作。
❓ 为什么使用 @lynx-js/react/compat
ReactLynx 通过 @lynx-js/react/compat 提供 React 18 API 兼容, 提供 TanStack
Router 所需的 API,如 React.startTransition。
lynx.config.js
路由配置
在 Lynx 环境中,document 为 undefined,导致错误地被识别为 isServer: true。你需要显式设置 isServer: false 来确保渲染的正确性。
此外,由于 Lynx 中浏览器 History API 的限制,需要使用 Memory Routing。
App.tsx
Polyfill
为了确保 URLSearchParams API 在 Lynx 环境中正常工作,请在入口文件顶部添加 url-search-params-polyfill:
index.tsx
File-Based
TanStack Router 支持基于文件结构定义路由。将路由组件放置在 src/routes 目录中,其中 __root.tsx 作为根组件。
src/routes/__root.tsx
src/routes/index.tsx
@tanstack/router-plugin/rspack 会自动扫描 src/routes 目录并生成包含所有路由定义和类型信息的 routeTree.gen.ts 文件。该生成文件包括:
- 路由配置
- 路由的 TypeScript 接口
- 完整的路由树结构
示例
