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

virtual-file-routes — скилл для Claude Code

Скилл virtual-file-routes для Claude Code строит деревья маршрутов программно как альтернативу файловым соглашениям. Запускается при правке конфигурации маршрутизатора в проекте.

MIT 108 установок ★ 15 341 обновлён 2026-10-25

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

Что делает virtual-file-routes

Скилл собирает маршруты через функции корневых узлов, индексов, путей, макетов и поддеревьев. Пути файлов задаются относительно директории маршрутов. Поддерживается вставка поддиректорий файлового роутинга.

Типы выводятся автоматически. Категорически запрещено использовать принудительное приведение типов.

Перед запуском требуется установить пакет @tanstack/virtual-file-routes через npm и передать конфигурацию в плагин роутера.

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

  • собрать дерево маршрутов программно через корневой узел и индекс
  • смонтировать директорию файловых маршрутов с префиксом пути
  • создать макет без добавления сегмента в URL
  • определить поддерево в конфигурации маршрутизации

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

  • Собери дерево маршрутов через rootRoute и добавь индексный маршрут
  • Добавь физическое монтирование папки через physical
  • Настрой конфигурацию виртуального поддерева через defineVirtualSubtreeConfig

Как установить virtual-file-routes

1Через Skills CLI (Vercel)

npx skills add TanStack/router --skill virtual-file-routes -a claude-code

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

~/.claude/skills/virtual-file-routes/SKILL.md

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

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

Вопросы о virtual-file-routes

Как установить virtual-file-routes в Claude Code?

Выполните команды npx skills add TanStack/router --skill virtual-file-routes -a claude-code и обратитесь к файлу ~/.claude/skills/virtual-file-routes/SKILL.md.

Что делает virtual-file-routes?

Строит деревья маршрутов программным способом без жёсткой привязки к файловой структуре.

Что нужно для работы virtual-file-routes?

Установленный пакет @tanstack/virtual-file-routes и плагин TanStack Router в конфигурации сборщика.

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

SKILL.md · MIT
---
name: virtual-file-routes
description: >-
  Programmatic route tree building as an alternative to filesystem
  conventions: rootRoute, index, route, layout, physical,
  defineVirtualSubtreeConfig. Use with TanStack Router plugin's
  virtualRouteConfig option.
metadata:
  type: core
  library: tanstack-router
  library_version: '1.162.0'
sources:
  - TanStack/router:packages/virtual-file-routes/src
  - TanStack/router:docs/router/routing/virtual-file-routes.md
---

# Virtual File Routes (`@tanstack/virtual-file-routes`)

Build route trees programmatically instead of relying on filesystem conventions. Useful when you want explicit control over route structure, need to mix virtual and physical routes, or want to define route subtrees within file-based routing directories.

Use this skill only when the project config contains `virtualRouteConfig`, a virtual route config file, or `__virtual.ts`. Ordinary file-route changes belong to Router Core and the Router Plugin.

> **CRITICAL**: Types are FULLY INFERRED. Never cast, never annotate inferred values.

## Install

```bash
npm install @tanstack/virtual-file-routes
```

## API Reference

### `rootRoute(file, children?)`

Creates the root of a virtual route tree.

```ts
import { rootRoute, index, route } from '@tanstack/virtual-file-routes'

const routes = rootRoute('root.tsx', [
  index('index.tsx'),
  route('/about', 'about.tsx'),
])
```

### `index(file)`

Creates an index route — the default rendered when the parent path matches exactly.

```ts
import { index } from '@tanstack/virtual-file-routes'

index('home.tsx')
```

### `route(path, ...)`

Creates a route node. Three call signatures:

```ts
import { route, index } from '@tanstack/virtual-file-routes'

// Leaf route: path + file
route('/about', 'about.tsx')

// Branch route: path + file + children
route('/dashboard', 'dashboard.tsx', [
  index('dashboard-index.tsx'),
  route('/settings', 'settings.tsx'),
])

// Path prefix only (no file): groups children under a URL segment
route('/api', [route('/users', 'users.tsx'), route('/posts', 'posts.tsx')])
```

### `layout(file, children)` or `layout(id, file, children)`

Creates a pathless layout route — wraps children without adding a URL segment.

```ts
import { layout, route, index } from '@tanstack/virtual-file-routes'

// ID derived from filename
layout('authLayout.tsx', [
  route('/dashboard', 'dashboard.tsx'),
  route('/settings', 'settings.tsx'),
])

// Explicit ID
layout('admin-layout', 'adminLayout.tsx', [route('/admin', 'admin.tsx')])
```

### `physical(pathPrefix, directory)` or `physical(directory)`

Mounts a directory of file-based routes at a URL prefix. Uses TanStack Router's standard file-based routing conventions within that directory.

```ts
import { physical } from '@tanstack/virtual-file-routes'

// Mount posts/ directory under /posts
physical('/posts', 'posts')

// Merge features/ directory at the current level
physical('features')
```

### `defineVirtualSubtreeConfig(config)`

Type helper for `__virtual.ts` files inside file-based routing directories. Identity function that provides type inference.

```ts
// src/routes/admin/__virtual.ts
import {
  defineVirtualSubtreeConfig,
  index,
  route,
} from '@tanstack/virtual-file-routes'

export default defineVirtualSubtreeConfig([
  index('home.tsx'),
  route('$id', 'details.tsx'),
])
```

## Integration with Router Plugin

Pass the virtual route config to the TanStack Router plugin:

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

export default defineConfig({
  plugins: [
    tanstackRouter({
      target: 'react', // or 'solid', 'vue'
      virtualRouteConfig: routes,
    }),
    // Add your framework's Vite plugin here
  ],
})
```

Or reference a file path:

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

## Full Example

```ts
// routes.ts
import {
  rootRoute,
  route,
  index,
  layout,
  physical,
} from '@tanstack/virtual-file-routes'

export const routes = rootRoute('root.tsx', [
  index('index.tsx'),

  layout('authLayout.tsx', [
    route('/dashboard', 'app/dashboard.tsx', [
      index('app/dashboard-index.tsx'),
      route('/invoices', 'app/dashboard-invoices.tsx', [
        index('app/invoices-index.tsx'),
        route('$id', 'app/invoice-detail.tsx'),
      ]),
    ]),
  ]),

  // Mount file-based routing from posts/ directory
  physical('/posts', 'posts'),
])
```

## Common Mistakes

### 1. HIGH: Forgetting that file paths are relative to routesDirectory

File paths in `rootRoute`, `index`, `route`, and `layout` are relative to the `routesDirectory` configured in the router plugin (default: `./src/routes`). Do not use absolute paths or paths relative to the project root.

```ts
// WRONG — absolute path
route('/about', '/src/routes/about.tsx')

// CORRECT — relative to routesDirectory
route('/about', 'about.tsx')
```

### 2. MEDIUM: Using physical() without matching directory structure

The directory passed to `physical()` must exist inside `routesDirectory` and follow TanStack Router's file-based routing conventions.

```ts
// WRONG — directory doesn't exist or wrong location
physical('/blog', 'src/blog')

// CORRECT — relative to routesDirectory
physical('/blog', 'blog')
// Expects: src/routes/blog/ (with route files inside)
```

### 3. MEDIUM: Confusing layout() with route()

`layout()` creates a pathless wrapper — it does NOT add a URL segment. Use `route()` for URL segments.

```ts
// This does NOT create a /dashboard URL
layout('dashboardLayout.tsx', [route('/dashboard', 'dashboard.tsx')])

// The URL is /dashboard, and dashboardLayout.tsx wraps it
```

## Refactor Audit

After changing a virtual tree:

1. Confirm there is exactly one `rootRoute` and that every referenced file exists relative to `routesDirectory`.
2. Check each `route`, `layout`, and `physical` node for duplicate effective paths or IDs.
3. Confirm each `physical()` directory is mounted once at the intended path prefix and does not overlap a virtual child.
4. Regenerate `routeTree.gen.ts` and inspect parentage, full paths, and imports. Do not edit generated output.
5. Update links, redirects, params, and `from` narrowing, then run generator tests, type tests, and a production build.

© TanStack · MIT · TanStack/router

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

Все скиллы по теме «Фронтенд и UI» →
tanstack-router oakoss Скилл tanstack-router настраивает типобезопасную файловую маршрутизацию в React через @tanstack/react-router. Помогает с лоадерами данных, валидацией параметров поиска и разделением кода. CX Codex +1 150установок tanstack-router-react-cursorrules-prompt-file PatrickJS Правило tanstack-router-react-cursorrules-prompt-file задаёт стандарты TanStack Router v1 в React: файловую маршрутизацию, валидацию search-параметров схемами Zod, загрузчики данных и защиту маршрутов через beforeLoad. CX Codex +1 ★ 41 178звёзд репо nextjs-dynamic-routes-params wsimmonds Скилл nextjs-dynamic-routes-params для Claude Code строит динамические сегменты App Router и читает params в Next.js 15+. Покрывает маршруты по ID или слагу. CX Codex +1 304установок tanstack-router-best-practices DeckardGer Скилл tanstack-router-best-practices для Claude Code: правила по TanStack Router для React — типизация, загрузка данных, search params и навигация. Структурирует роутинг в растущих проектах. CX Codex +1 7 200установок tanstack-start-cursorrules-prompt-file PatrickJS Правило tanstack-start-cursorrules-prompt-file для Cursor описывает структуру TanStack Start и типобезопасную разработку с SSR. Активируется в проектах Start, маршрутах TanStack Router и конфигурации Vinxi. CX Codex +1 ★ 41 178звёзд репо azure-virtual-network MicrosoftDocs Скилл azure-virtual-network с документацией Microsoft по проектированию и настройке виртуальных сетей Azure. Помогает с подсетями, маршрутизацией, NSG, пирингом и безопасностью сети. CX Codex +1 217установок

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

Весь набор →
deployment Скилл deployment разворачивает приложения TanStack Start на Cloudflare Workers, Netlify, Vercel, Node.js, Bun и Railway. Управляет SSR по маршрутам, статическим пререндерингом и SEO. CX Codex +1 210установок path-params Скилл path-params для работы с динамическими параметрами в URL-адресах маршрутов TanStack Router. Позволяет захватывать переменные части пути, настраивать опциональные сегменты и создавать шаблоны с префиксами и суффиксами. CX Codex +1 208установок middleware Учит работать с middleware-цепочками TanStack Start. Покрывает createMiddleware, передачу контекста через next(), sendContext и глобальные хуки через src/start.ts. CX Codex +1 206установок server-routes Скилл server-routes для Claude Code создаёт серверные API-маршруты в TanStack Router и разбирает HTTP-запросы. Эндпоинты размещаются рядом с маршрутами приложения. CX Codex +1 205установок ssr Скилл ssr помогает настроить серверный рендеринг в TanStack Router: потоковый или обычный. Пригодится при интеграции роутера с существующим сервером. CX Codex +1 202установок auth-server-primitives Скилл auth-server-primitives для Claude Code помогает собрать серверную часть аутентификации в TanStack Start. Он включается при работе с сессиями, OAuth, сбросом пароля и защитой серверных функций. CX Codex +1 201установок migrate-from-react-router Скилл migrate-from-react-router для Claude Code ведёт по шагам переезда с React Router v7 на TanStack Router: от конвертации маршрутов до навигации и search-параметров. CX Codex +1 188установок bundle-size-optimization Скилл bundle-size-optimization для Claude Code измеряет клиентские бандлы TanStack Router и сравнивает кандидатов с сохранённым базовым замером. Проверяет, вырос ли gzip после правки. CX Codex +1 139установок

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

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