[ PROMPT_NODE_24806 ]
路由指南
[ SKILL_DOCUMENTATION ]
# 路由指南
TanStack Router 实现,包含基于文件夹的路由和懒加载模式。
---
## TanStack Router 概览
**TanStack Router** 采用基于文件的路由:
- 文件夹结构定义路由
- 用于代码分割的懒加载
- 类型安全的路由
- 面包屑加载器
---
## 基于文件夹的路由
### 目录结构
routes/
__root.tsx # 根布局
index.tsx # 首页路由 (/)
posts/
index.tsx # /posts
create/
index.tsx # /posts/create
$postId.tsx # /posts/:postId (动态)
comments/
index.tsx # /comments
**模式**:
- `index.tsx` = 该路径下的路由
- `$param.tsx` = 动态参数
- 嵌套文件夹 = 嵌套路由
---
## 基础路由模式
### posts/index.tsx 示例
typescript
/**
* 文章路由组件
* 显示主博客文章列表
*/
import { createFileRoute } from '@tanstack/react-router';
import { lazy } from 'react';
// 懒加载页面组件
const PostsList = lazy(() =>
import('@/features/posts/components/PostsList').then(
(module) => ({ default: module.PostsList }),
),
);
export const Route = createFileRoute('/posts/')({
component: PostsPage,
// 定义面包屑数据
loader: () => ({
crumb: 'Posts',
}),
});
function PostsPage() {
return (
);
}
export default PostsPage;
**关键点:**
- 懒加载大型组件
- 使用 `createFileRoute` 定义路由路径
- 使用 `loader` 获取面包屑数据
- 页面组件渲染内容
- 同时导出 Route 和组件
---
## 懒加载路由
### 命名导出模式
typescript
import { lazy } from 'react';
// 对于命名导出,使用 .then() 映射到 default
const MyPage = lazy(() =>
import('@/features/my-feature/components/MyPage').then(
(module) => ({ default: module.MyPage })
)
);
### 默认导出模式
typescript
import { lazy } from 'react';
// 对于默认导出,语法更简单
const MyPage = lazy(() => import('@/features/my-feature/components/MyPage'));
### 为什么要懒加载路由?
- 代码分割 - 减小初始包体积
- 更快的初始页面加载
- 仅在导航到时加载路由代码
- 更好的性能
---
## createFileRoute
### 基本配置
typescript
export const Route = createFileRoute('/my-route/'