Skip to content
安装与快速开始

安装与快速开始

TanStack Router 是 TanStack 生态中的端到端类型安全路由库,专为 React 和 Solid 应用设计。它提供 100% 推断的 TypeScript 支持,涵盖路径参数、搜索参数、Loader、导航等所有环节。

官方文档:TanStack Router 安装:npm install @tanstack/react-router


前置条件

  • React:18.0 或更高版本
  • TypeScript:5.3+(强烈推荐,类型安全是 TanStack Router 的核心卖点)
  • Vite(推荐)或其他支持代码生成的构建工具

创建项目

方式一:CLI 脚手架(推荐新项目)

npx @tanstack/cli create --router-only

这会创建一个预配置好的 Vite + React + TanStack Router 项目。

方式二:手动添加到已有项目

npm install @tanstack/react-router
npm install -D @tanstack/router-plugin @tanstack/router-devtools

💡 最佳实践:TanStack Router 支持基于文件的路由(File-Based Routing)和基于代码的路由(Code-Based Routing)。新项目推荐使用文件路由,与 Vite 插件配合可以自动生成类型安全的路由树。


Vite 配置

// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { tanstackRouter } from '@tanstack/router-plugin/vite'

export default defineConfig({
  plugins: [
    // 🚨 tanstackRouter 必须在 react 插件之前
    tanstackRouter({
      // 可选:启用自动代码分割
      autoCodeSplitting: true,
    }),
    react(),
  ],
})

🚨 陷阱tanstackRouter 插件必须在 @vitejs/plugin-react 之前,否则路由树文件(routeTree.gen.ts)无法正确生成。


项目结构(文件路由)

src/
├── main.tsx                    # 应用入口
├── App.tsx                     # 根组件(可选,内联到 main.tsx 也行)
├── router.tsx                  # 路由实例创建 + 类型注册
├── routes/
│   ├── __root.tsx              # 根路由(Root Route)
│   ├── index.tsx               # 首页 → /
│   ├── about.tsx               # 关于页 → /about
│   ├── posts/
│   │   ├── index.tsx           # 帖子列表 → /posts
│   │   └── $postId.tsx         # 帖子详情 → /posts/:postId
│   └── _authenticated/         # 路径无关的布局路由(pathless layout)
│       ├── dashboard.tsx        # → /dashboard
│       └── settings.tsx         # → /settings

命名约定

文件名 对应路径 说明
__root.tsx / 根路由,所有路由的顶层包装
index.tsx /目录路径 目录的默认路由
$param.tsx /:param 动态路径参数
_layout.tsx 无(pathless) _ 开头的路径段不会出现在 URL 中
$.tsx /* Catch-all / splat 路由

💡 最佳实践_ 前缀的路径段是"路径无关布局"(Pathless Layout),用于组织认证守卫、共享布局等,不会影响 URL 结构。


第一个路由

1. 创建根路由

// src/routes/__root.tsx
import { createRootRoute, Outlet } from '@tanstack/react-router'

export const Route = createRootRoute({
  component: () => (
    <div>
      <header>
        <h1>我的应用</h1>
        <nav>
          <Link to="/">首页</Link>
          <Link to="/about">关于</Link>
        </nav>
      </header>
      <main>
        <Outlet />
      </main>
    </div>
  ),
  notFoundComponent: () => <div>404 - 页面未找到</div>,
})

2. 创建首页路由

// src/routes/index.tsx
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/')({
  component: () => <h2>欢迎来到首页!</h2>,
})

3. 创建路由器实例

// src/router.tsx
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen' // 由 Vite 插件自动生成

const router = createRouter({ routeTree })

// 🚨 关键!注册类型以获得全局类型安全
declare module '@tanstack/react-router' {
  interface Register {
    router: typeof router
  }
}

export { router }

🚨 陷阱务必router.tsx 中进行 declare module 类型注册。没有它,整个应用的类型推断将无法工作——LinkuseSearchuseParams 等所有 Hook 都会失去类型安全。

4. 挂载应用

// src/main.tsx
import { RouterProvider } from '@tanstack/react-router'
import { router } from './router'

function App() {
  return <RouterProvider router={router} />
}

export default App
// index.tsx / main.tsx entry
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

快速检查清单

  • 安装了 @tanstack/react-router@tanstack/router-plugin
  • vite.config.tstanstackRouter 插件在 react 之前
  • 创建了 __root.tsx 根路由
  • 创建了 router.tsx 并完成 declare module 类型注册
  • main.tsx 中使用 <RouterProvider> 挂载路由
  • npm run dev 正常启动,路由跳转工作正常