router-plugin
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRouter Plugin (@tanstack/router-plugin
)
@tanstack/router-plugin路由插件(@tanstack/router-plugin
)
@tanstack/router-pluginBundler plugin that powers TanStack Router's file-based routing and automatic code splitting. Works with Vite, Webpack, Rspack, and esbuild via unplugin.
CRITICAL: The router plugin MUST come before the framework plugin (React, Solid, Vue) in the Vite config. Wrong order causes route generation and code splitting to fail silently.
为TanStack Router的文件路由和自动代码分割提供支持的打包器插件,通过unplugin兼容Vite、Webpack、Rspack和esbuild。
重要提示:在Vite配置中,router插件必须放在框架插件(React、Solid、Vue)之前,顺序错误会导致路由生成和代码分割静默失败。
Install
安装
bash
npm install -D @tanstack/router-pluginbash
npm install -D @tanstack/router-pluginBundler Setup
打包器配置
Vite (most common)
Vite(最常用)
ts
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { tanstackRouter } from '@tanstack/router-plugin/vite'
export default defineConfig({
plugins: [
// MUST come before react()
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
}),
react(),
],
})ts
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { tanstackRouter } from '@tanstack/router-plugin/vite'
export default defineConfig({
plugins: [
// 必须放在react()之前
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
}),
react(),
],
})Webpack
Webpack
ts
// webpack.config.js
const { tanstackRouter } = require('@tanstack/router-plugin/webpack')
module.exports = {
plugins: [
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
}),
],
}ts
// webpack.config.js
const { tanstackRouter } = require('@tanstack/router-plugin/webpack')
module.exports = {
plugins: [
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
}),
],
}Rspack
Rspack
ts
// rspack.config.js
const { tanstackRouter } = require('@tanstack/router-plugin/rspack')
module.exports = {
plugins: [
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
}),
],
}ts
// rspack.config.js
const { tanstackRouter } = require('@tanstack/router-plugin/rspack')
module.exports = {
plugins: [
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
}),
],
}esbuild
esbuild
ts
import { tanstackRouter } from '@tanstack/router-plugin/esbuild'
import esbuild from 'esbuild'
esbuild.build({
plugins: [
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
}),
],
})ts
import { tanstackRouter } from '@tanstack/router-plugin/esbuild'
import esbuild from 'esbuild'
esbuild.build({
plugins: [
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
}),
],
})Configuration Options
配置选项
Core Options
核心选项
| Option | Type | Default | Description |
|---|---|---|---|
| | | Target framework |
| | | Directory containing route files |
| | | Path for generated route tree |
| | | Enable automatic code splitting |
| | | Set to |
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | | 目标框架 |
| | | 存放路由文件的目录 |
| | | 生成的路由树文件输出路径 |
| | | 启用自动代码分割 |
| | | 设置为 |
File Convention Options
文件约定选项
| Option | Type | Default | Description |
|---|---|---|---|
| | | Prefix filter for route files |
| | | Prefix to exclude files from routing |
| | | Pattern to exclude from routing |
| | | Token identifying index routes |
| | | Token identifying route config files |
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | | 路由文件的前缀过滤规则 |
| | | 需排除在路由外的文件前缀 |
| | | 需排除在路由外的文件匹配规则 |
| | | 标识首页路由的标记 |
| | | 标识路由配置文件的标记 |
Code Splitting Options
代码分割选项
ts
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
codeSplittingOptions: {
// Default groupings for all routes
defaultBehavior: [['component'], ['errorComponent'], ['notFoundComponent']],
// Per-route custom splitting
splitBehavior: ({ routeId }) => {
if (routeId === '/dashboard') {
// Keep loader and component together for dashboard
return [['loader', 'component'], ['errorComponent']]
}
// Return undefined to use defaultBehavior
},
},
})ts
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
codeSplittingOptions: {
// 所有路由的默认分组规则
defaultBehavior: [['component'], ['errorComponent'], ['notFoundComponent']],
// 单路由自定义分割规则
splitBehavior: ({ routeId }) => {
if (routeId === '/dashboard') {
// 仪表板页面的loader和component打包在同一分组
return [['loader', 'component'], ['errorComponent']]
}
// 返回undefined则使用defaultBehavior规则
},
},
})Output Options
输出选项
| Option | Type | Default | Description |
|---|---|---|---|
| | | Quote style in generated code |
| | | Use semicolons in generated code |
| | | Disable TypeScript types |
| | | Suppress plugin logs |
| | | Add file extensions to imports |
| | | Format generated route tree |
| | | When |
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | | 生成代码的引号风格 |
| | | 生成代码是否使用分号 |
| | | 关闭TypeScript类型声明 |
| | | 关闭插件日志输出 |
| | | 为导入语句添加文件后缀 |
| | | 格式化生成的路由树代码 |
| | | 设置为 |
Virtual Route Config
虚拟路由配置
ts
import { routes } from './routes'
tanstackRouter({
target: 'react',
virtualRouteConfig: routes, // or './routes.ts'
})ts
import { routes } from './routes'
tanstackRouter({
target: 'react',
virtualRouteConfig: routes, // 也可以填文件路径 './routes.ts'
})How It Works
工作原理
The composed plugin assembles up to 4 sub-plugins:
- Route Generator (always) — Watches route files and generates
routeTree.gen.ts - Code Splitter (when ) — Splits route files into lazy-loaded chunks using virtual modules
autoCodeSplitting: true - Auto-Import (when ) — Auto-injects
verboseFileRoutes: falseimportscreateFileRoute - HMR (dev mode, when code splitter is off) — Hot-reloads route changes without full refresh
组合后的插件最多包含4个子插件:
- 路由生成器(始终启用)—— 监听路由文件变化并生成
routeTree.gen.ts - 代码分割器(时启用)—— 通过虚拟模块将路由文件拆分为懒加载块
autoCodeSplitting: true - 自动导入插件(时启用)—— 自动注入
verboseFileRoutes: false导入语句createFileRoute - HMR插件(开发模式且代码分割器关闭时启用)—— 路由变更热重载无需全量刷新
Individual Plugin Exports
单独子插件导出
For advanced use, each sub-plugin is exported separately from the Vite entry:
ts
import {
tanstackRouter, // Composed (default)
tanstackRouterGenerator, // Generator only
tanStackRouterCodeSplitter, // Code splitter only
tanstackRouterAutoImport, // Auto-import only
} from '@tanstack/router-plugin/vite'针对高级使用场景,所有子插件都可以从Vite入口单独导出:
ts
import {
tanstackRouter, // 组合版(默认)
tanstackRouterGenerator, // 仅路由生成器
tanStackRouterCodeSplitter, // 仅代码分割器
tanstackRouterAutoImport, // 仅自动导入插件
} from '@tanstack/router-plugin/vite'Common Mistakes
常见错误
1. CRITICAL: Wrong plugin order in Vite config
1. 严重:Vite配置中插件顺序错误
The router plugin must come before the framework plugin. Otherwise, route generation and code splitting fail silently.
ts
// WRONG — react() before tanstackRouter()
plugins: [react(), tanstackRouter({ target: 'react' })]
// CORRECT — tanstackRouter() first
plugins: [tanstackRouter({ target: 'react' }), react()]路由插件必须放在框架插件之前,否则路由生成和代码分割会静默失败。
ts
// 错误 —— react()放在tanstackRouter()之前
plugins: [react(), tanstackRouter({ target: 'react' })]
// 正确 —— tanstackRouter()放在最前
plugins: [tanstackRouter({ target: 'react' }), react()]2. HIGH: Missing target option for non-React frameworks
2. 高优先级:非React框架未指定target选项
The defaults to . For Solid or Vue, you must set it explicitly.
target'react'ts
// WRONG for Solid — generates React imports
tanstackRouter({ autoCodeSplitting: true })
// CORRECT for Solid
tanstackRouter({ target: 'solid', autoCodeSplitting: true })target'react'ts
// Solid框架错误写法 —— 会生成React相关导入语句
tanstackRouter({ autoCodeSplitting: true })
// Solid框架正确写法
tanstackRouter({ target: 'solid', autoCodeSplitting: true })3. MEDIUM: Confusing autoCodeSplitting with manual lazy routes
3. 中优先级:开启autoCodeSplitting后仍手动编写懒路由
When is enabled, the plugin handles splitting automatically. You do NOT need manual or calls — the plugin transforms your route files at build time.
autoCodeSplittingcreateLazyRoutelazyRouteComponenttsx
// WRONG — manual lazy loading with autoCodeSplitting enabled
const LazyAbout = lazyRouteComponent(() => import('./about'))
// CORRECT — just write normal route files, plugin handles splitting
// src/routes/about.tsx
export const Route = createFileRoute('/about')({
component: AboutPage,
})
function AboutPage() {
return <h1>About</h1>
}启用后,插件会自动处理代码分割,你不需要手动调用或者——插件会在构建阶段自动转换路由文件。
autoCodeSplittingcreateLazyRoutelazyRouteComponenttsx
// 错误 —— 开启autoCodeSplitting后仍手动懒加载
const LazyAbout = lazyRouteComponent(() => import('./about'))
// 正确 —— 正常编写路由文件即可,插件会处理分割
// src/routes/about.tsx
export const Route = createFileRoute('/about')({
component: AboutPage,
})
function AboutPage() {
return <h1>关于我们</h1>
}Cross-References
相关参考
- router-core/code-splitting — manual code splitting concepts
- virtual-file-routes — programmatic route trees
- router-core/code-splitting —— 手动代码分割相关概念
- virtual-file-routes —— 程序化路由树使用指南