К основному содержанию
скилл CX Codex

router-plugin — скилл для Claude Code: что делает и как установить

Настраивает плагин сборщика для генерации маршрутов и разделения кода в TanStack Router. Помогает подключить Vite, Webpack, Rspack или esbuild.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add TanStack/router --skill router-plugin -a claude-code
Открыть на GitHub

Что делает router-plugin

Скилл помогает настроить пакет @tanstack/router-plugin для проектов на React, Solid или Vue. Плагин непрерывно отслеживает файлы внутри routesDirectory и собирает их в единый файл routeTree.gen.ts. Если включён флаг autoCodeSplitting, плагин автоматически нарезает компоненты и загрузчики на изолированные чанки через виртуальные модули.

В конфигурации Vite плагин обязан стоять строго до плагина фреймворка вроде @vitejs/plugin-react. При неверном порядке генерация дерева тихо сломается. Никогда не правьте routeTree.gen.ts вручную. При любых рефакторингах путей меняйте исходные файлы и давайте плагину или утилите pnpm exec tsr generate обновить дерево самостоятельно.

Какие задачи решает

  • настроить сборку routeTree.gen.ts по структуре файлов
  • включить автоматическое разделение кода через autoCodeSplitting
  • сконфигурировать плагин для Vite, Webpack, Rspack или esbuild
  • задать правила игнорирования файлов в каталоге маршрутов

Примеры запросов агенту

  • Покажи, как подключить router-plugin в vite.config.ts для React
  • Как настроить splitBehavior в codeSplittingOptions для конкретного routeId?
  • Помоги перенести файлы маршрутов в routesDirectory без ручной правки routeTree.gen.ts

Как установить router-plugin

1Через Skills CLI (Vercel)

npx skills add TanStack/router --skill router-plugin -a claude-code

2Вручную: положить файлы

~/.claude/skills/router-plugin/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/router-plugin/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о router-plugin

Как установить router-plugin в Claude Code?

Выполните команду npx skills add TanStack/router --skill router-plugin -a claude-code.

Что делает router-plugin?

Он следит за файлами маршрутов, создаёт routeTree.gen.ts и делит компоненты страниц на ленивые бандлы.

Почему в Vite важен порядок плагинов?

Вызов tanstackRouter обязательно должен идти раньше react(). Иначе генерация маршрутов и разделение кода молча перестанут работать.

Исходный текст

SKILL.md · MIT
---
name: router-plugin
description: >-
  TanStack Router bundler plugin for route generation and automatic
  code splitting. Supports Vite, Webpack, Rspack, and esbuild.
  Configures autoCodeSplitting, routesDirectory, target framework,
  and code split groupings.
metadata:
  type: core
  library: tanstack-router
  library_version: '1.168.23'
sources:
  - TanStack/router:packages/router-plugin/src
  - TanStack/router:docs/router/routing/file-based-routing.md
  - TanStack/router:docs/router/guide/code-splitting.md
---

# 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.

## Install

```bash
npm install -D @tanstack/router-plugin
```

## Bundler Setup

### Vite (most common)

```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(),
  ],
})
```

### Webpack

```ts
// webpack.config.js
const { tanstackRouter } = require('@tanstack/router-plugin/webpack')

module.exports = {
  plugins: [
    tanstackRouter({
      target: 'react',
      autoCodeSplitting: true,
    }),
  ],
}
```

### Rspack

```ts
// rspack.config.js
const { tanstackRouter } = require('@tanstack/router-plugin/rspack')

module.exports = {
  plugins: [
    tanstackRouter({
      target: 'react',
      autoCodeSplitting: true,
    }),
  ],
}
```

### esbuild

```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`             | `'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  |

### File Convention Options

| Option                   | Type                                                    | Default     | Description                          |
| ------------------------ | ------------------------------------------------------- | ----------- | ------------------------------------ |
| `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 |

### 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
    },
  },
})
```

### Output Options

| Option                      | Type                   | Default    | Description                      |
| --------------------------- | ---------------------- | ---------- | -------------------------------- |
| `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      |

### Virtual Route Config

```ts
import { routes } from './routes'

tanstackRouter({
  target: 'react',
  virtualRouteConfig: routes, // or './routes.ts'
})
```

## How It Works

The composed plugin assembles up to 3 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. **HMR** (dev mode, when code splitter is off) — Hot-reloads route changes without full refresh

## Route Refactor Workflow

When moving, renaming, adding, or deleting file routes:

1. Change the source files under `routesDirectory`. Keep the exported route identifier named `Route`.
2. Let the bundler plugin regenerate the tree, or run `pnpm exec tsr generate` when the project uses the CLI.
3. Inspect the generated diff for the expected route IDs, parents, paths, and imports. Never repair `routeTree.gen.ts` by hand.
4. Update links, redirects, `from` narrowing, params, preload calls, and tests that reference the old route.
5. Run route-generation tests, type tests, and a production build. A passing editor typecheck does not prove the plugin generated or split the new route correctly.

Commit `routeTree.gen.ts`; it is generated source used by the application at runtime.

## 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
} from '@tanstack/router-plugin/vite'
```

## Common Mistakes

### 1. CRITICAL: Wrong plugin order in Vite config

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()]
```

### 2. HIGH: Missing target option for non-React frameworks

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 })
```

### 3. MEDIUM: Confusing autoCodeSplitting with manual lazy routes

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>
}
```

### 4. HIGH: Editing the generated route tree

Changes to `routeTree.gen.ts` are overwritten and can leave source routes, generated types, and runtime routing out of sync. Fix route filenames or plugin configuration, regenerate, and verify the generated diff instead.

## Cross-References

- `@tanstack/router-core#router-core/code-splitting` — manual code splitting concepts
- `@tanstack/virtual-file-routes#virtual-file-routes` — programmatic route trees

© TanStack · MIT · TanStack/router

Похожие скиллы

Всё по теме «Фронтенд и UI» →
plugin-bundle-size grafana Помогает уменьшить размер входного файла module.js в плагинах приложений Grafana через React.lazy и разделение чанков в Webpack. CX Codex +1 4 200установок tanstack-router-best-practices DeckardGer Набор правил по TanStack Router для React: типизация, загрузка данных, search params и навигация. Пригодится, когда роутинг в проекте разрастается. CX Codex +1 7 100установок react-vite-best-practices agent-skills Скилл с 23 правилами оптимизации React-приложений на Vite: сборка, code splitting, HMR, ассеты, переменные окружения и анализ бандла. Пригодится, когда агент пишет или ревьюит компоненты. CX Codex +1 2 900установок tanstack-router PatrickJS Правило для Cursor, которое задаёт агенту стандарты TanStack Router v1: файловые маршруты, типизация параметров и загрузка данных через loader. ★ 41 011звёзд репо vite-bundle-optimization patterns.dev Скилл с паттернами оптимизации бандла и сборки в Vite + React. Пригодится, когда билд тормозит или чанки выходят больше ожидаемого. CX Codex +1 667установок react-performance-optimization NickCrew Помогает находить узкие места в рендере React, настраивать мемоизацию, разделение кода и виртуализацию списков. Пригодится для ускорения медленных экранов и уменьшения бандла. CX Codex +1 1 900установок

Из того же набора7

router-core Скилл-навигатор по TanStack Router: разводит задачу по подскиллам и напоминает про вывод типов и клиентские лоадеры, на которых агенты ломаются. CX Codex +1 589установок react-router Скилл для агента по @tanstack/react-router: справочник хуков и компонентов плюс сборка файлового роутинга на Vite от установки до routeTree.gen. CX Codex +1 547установок react-start Правила и шаблоны для проектов на TanStack Start с React. Помогает агенту писать изоморфный код, настраивать Vite и связывать серверные функции с UI. CX Codex +1 454установок start-core Скилл объясняет базовую структуру TanStack Start: Vite-плагин, роутер, корневой маршрут и серверные функции. Нужен при создании или проверке Start-проекта. CX Codex +1 447установок router-query Связывает TanStack Router с TanStack Query для предзагрузки данных в лоадерах, кэширования через useSuspenseQuery и изоляции QueryClient при SSR. CX Codex +1 366установок start-server-core Скилл по серверному рантайму TanStack Start: обработчик запроса, утилиты запроса и ответа, работа с куками. Пригодится, когда серверная часть Start уже есть в проекте. CX Codex +1 355установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой