router-plugin

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Router Plugin (
@tanstack/router-plugin
)

路由插件(
@tanstack/router-plugin

Bundler 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-plugin
bash
npm install -D @tanstack/router-plugin

Bundler 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

核心选项

OptionTypeDefaultDescription
target
'react' | 'solid' | 'vue'
'react'
Target framework
routesDirectory
string
'./src/routes'
Directory containing route files
generatedRouteTree
string
'./src/routeTree.gen.ts'
Path for generated route tree
autoCodeSplitting
boolean
undefined
Enable automatic code splitting
enableRouteGeneration
boolean
true
Set to
false
to disable route generation
选项类型默认值说明
target
'react' | 'solid' | 'vue'
'react'
目标框架
routesDirectory
string
'./src/routes'
存放路由文件的目录
generatedRouteTree
string
'./src/routeTree.gen.ts'
生成的路由树文件输出路径
autoCodeSplitting
boolean
undefined
启用自动代码分割
enableRouteGeneration
boolean
true
设置为
false
可关闭路由生成功能

File Convention Options

文件约定选项

OptionTypeDefaultDescription
routeFilePrefix
string
undefined
Prefix filter for route files
routeFileIgnorePrefix
string
'-'
Prefix to exclude files from routing
routeFileIgnorePattern
string
undefined
Pattern to exclude from routing
indexToken
string | RegExp | { regex: string; flags?: string }
'index'
Token identifying index routes
routeToken
string | RegExp | { regex: string; flags?: string }
'route'
Token identifying route config files
选项类型默认值说明
routeFilePrefix
string
undefined
路由文件的前缀过滤规则
routeFileIgnorePrefix
string
'-'
需排除在路由外的文件前缀
routeFileIgnorePattern
string
undefined
需排除在路由外的文件匹配规则
indexToken
string | RegExp | { regex: string; flags?: string }
'index'
标识首页路由的标记
routeToken
string | RegExp | { regex: string; flags?: string }
'route'
标识路由配置文件的标记

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

输出选项

OptionTypeDefaultDescription
quoteStyle
'single' | 'double'
'single'
Quote style in generated code
semicolons
boolean
false
Use semicolons in generated code
disableTypes
boolean
false
Disable TypeScript types
disableLogging
boolean
false
Suppress plugin logs
addExtensions
boolean | string
false
Add file extensions to imports
enableRouteTreeFormatting
boolean
true
Format generated route tree
verboseFileRoutes
boolean
undefined
When
false
, auto-imports
createFileRoute
选项类型默认值说明
quoteStyle
'single' | 'double'
'single'
生成代码的引号风格
semicolons
boolean
false
生成代码是否使用分号
disableTypes
boolean
false
关闭TypeScript类型声明
disableLogging
boolean
false
关闭插件日志输出
addExtensions
boolean | string
false
为导入语句添加文件后缀
enableRouteTreeFormatting
boolean
true
格式化生成的路由树代码
verboseFileRoutes
boolean
undefined
设置为
false
时自动导入
createFileRoute

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:
  1. Route Generator (always) — Watches route files and generates
    routeTree.gen.ts
  2. Code Splitter (when
    autoCodeSplitting: true
    ) — Splits route files into lazy-loaded chunks using virtual modules
  3. Auto-Import (when
    verboseFileRoutes: false
    ) — Auto-injects
    createFileRoute
    imports
  4. HMR (dev mode, when code splitter is off) — Hot-reloads route changes without full refresh
组合后的插件最多包含4个子插件:
  1. 路由生成器(始终启用)—— 监听路由文件变化并生成
    routeTree.gen.ts
  2. 代码分割器
    autoCodeSplitting: true
    时启用)—— 通过虚拟模块将路由文件拆分为懒加载块
  3. 自动导入插件
    verboseFileRoutes: false
    时启用)—— 自动注入
    createFileRoute
    导入语句
  4. 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
target
defaults to
'react'
. For Solid or Vue, you must set it explicitly.
ts
// WRONG for Solid — generates React imports
tanstackRouter({ autoCodeSplitting: true })

// CORRECT for Solid
tanstackRouter({ target: 'solid', autoCodeSplitting: true })
target
默认值为
'react'
,如果使用Solid或Vue框架,必须显式设置。
ts
// Solid框架错误写法 —— 会生成React相关导入语句
tanstackRouter({ autoCodeSplitting: true })

// Solid框架正确写法
tanstackRouter({ target: 'solid', autoCodeSplitting: true })

3. MEDIUM: Confusing autoCodeSplitting with manual lazy routes

3. 中优先级:开启autoCodeSplitting后仍手动编写懒路由

When
autoCodeSplitting
is enabled, the plugin handles splitting automatically. You do NOT need manual
createLazyRoute
or
lazyRouteComponent
calls — the plugin transforms your route files at build time.
tsx
// 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>
}
启用
autoCodeSplitting
后,插件会自动处理代码分割,你不需要手动调用
createLazyRoute
或者
lazyRouteComponent
——插件会在构建阶段自动转换路由文件。
tsx
// 错误 —— 开启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 —— 程序化路由树使用指南