安装与项目结构

环境要求

  • Node.js 20+ 或 Bun
  • React 与 TypeScript 基础
  • 推荐 VS Code + TypeScript 插件

创建项目

官方脚手架命令会随版本变化,优先参考最新文档。常见方式:

npm create tanstack@latest

或使用 Bun:

bun create tanstack

选择模板时确认:框架为 React、启用 Start、构建工具为 Vite 或 Rsbuild。

关键依赖

{
  "dependencies": {
    "@tanstack/react-start": "<pin-exact-version>",
    "@tanstack/react-router": "<pin-exact-version>",
    "@tanstack/router-plugin": "<pin-exact-version>",
    "react": "^19.0.0",
    "react-dom": "^19.0.0"
  }
}

RC 阶段建议锁定精确版本,避免小版本变化影响路由生成或服务端函数。

典型目录

src/
├── routes/
│   ├── __root.tsx
│   ├── index.tsx
│   └── posts.$postId.tsx
├── routeTree.gen.ts
├── router.tsx
└── start.ts
文件作用
routes/文件路由目录
__root.tsx根路由、HTML shell、Outlet、错误边界
routeTree.gen.ts由插件生成的路由树
router.tsx创建 Router 实例与 context
start.tsMiddleware、CSRF、服务端入口配置

Vite 插件

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import { TanStackRouterVite } from '@tanstack/router-plugin/vite'

export default defineConfig({
  plugins: [TanStackRouterVite(), tanstackStart(), react()],
})

插件顺序和包名以官方模板为准。

下一步