К основному содержанию
скилл Claude Code CX Codex Cursor GitHub Copilot

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

Скилл-навигатор по TanStack Router: разводит задачу по подскиллам и напоминает про вывод типов и клиентские лоадеры, на которых агенты ломаются.

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

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

Скилл router-core открывает набор скиллов по TanStack Router. Его дело — развести задачу по подскиллам: параметры поиска, динамические сегменты, навигация, загрузка данных, гарды, code splitting, 404 и ошибки, типы, SSR. Для этого внутри есть таблица соответствий и дерево решений, так что агент открывает один нужный файл. Второй подскилл подгружается, только когда задача правда пересекает границу: скажем, авторизованный лоадер тянет сразу auth-and-guards и data-loading.

Ядро фреймворк-агностично, биндинги для React и Solid лежат сверху. Скилл задаёт два правила. Типы TanStack Router выводятся полностью, поэтому касты и ручные аннотации только портят дело. Лоадеры по умолчанию работают на клиенте, а не на сервере, как в Next.js или Remix, и путать API этих роутеров нельзя. Ещё он напоминает, что строку пути в createFileRoute пишет плагин, а не человек.

Скилл написан под @tanstack/router-core v1.171.15: сплаты используют $, совместимый алиас * уйдёт в v2. Отдельный блок — проверки после рефакторинга: переименовать файл роута, перегенерировать routeTree.gen.ts, обновить ссылки и прогнать сборку, потому что один typecheck ничего не доказывает. Блок declare module '@tanstack/react-router' с интерфейсом Register обязателен: без него у Link и useNavigate нет автодополнения. Это повод добавить его сразу, а не искать причину пустых подсказок позже.

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

  • выбрать нужный подскилл под задачу по роутингу
  • подключить Register и вернуть автодополнение в Link и useNavigate
  • перегенерировать routeTree.gen.ts после переименования файла роута
  • поймать путь в createFileRoute, разошедшийся с расположением файла
  • разобраться, где живут лоадеры — на клиенте или на сервере

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

  • Подключи TanStack Router: сделай `__root.tsx`, роут `/posts/$postId` и `createRouter` с `routeTree`
  • Не работает автодополнение в `Link` — проверь `Register` по скиллу router-core
  • Переименовал файл роута: перегенерируй `routeTree.gen.ts` и обнови все ссылки

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

1Через Skills CLI (Vercel)

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

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

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

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

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

Весь набор →

Похожие

cli-anything-anygen HKUDS Инструмент даёт агенту доступ к AnyGen OpenAPI для генерации слайдов и диаграмм. Пригодится при автоматической сборке документов через терминал. Claude Code CX Codex Cursor +1 465установок architect backnotprop Проектирует типы, сигнатуры и структуру модулей до написания кода, предотвращая неверную архитектуру в нетривиальных задачах. Claude Code CX Codex Cursor +1 5 300установок arena backnotprop Запускает несколько параллельных попыток на одну задачу, оценивает их по рубрике и переносит сильные куски проигравших в выбранную базу. Claude Code CX Codex Cursor +1 5 300установок figure-it-out backnotprop Скилл для задач без готового рецепта: сначала проектирует план работ и критерий готовности, потом идёт по гипотезам и пишет журнал решений для проверяющего. Claude Code CX Codex Cursor +1 5 100установок gpt-image wuyoscar Скилл превращает просьбу «нарисуй» или «поправь» в вызов готового CLI: уточняет модель, размер и текст на картинке, затем отдаёт путь к файлу. Claude Code CX Codex Cursor +1 553установок principle-redesign-from-first-principles backnotprop Скилл учит агента не прикручивать новые требования к готовому дизайну, а перестраивать его так, будто требование было с самого начала. Пригодится, когда правка затрагивает несколько файлов и связей. Claude Code CX Codex Cursor +1 5 000установок setup-matt-pocock-skills Matt Pocock Скилл настраивает репозиторий для инженерных скиллов Matt Pocock: задаёт трекер задач, метки триажа и расположение доменной документации. Запустите его перед первым использованием остальных скиллов. Claude Code 1 052 851установок to-tickets Matt Pocock Разбивает план, спецификацию или переписку на небольшие сквозные задачи и отмечает, какие из них блокируют остальные. Пригодится, когда нужно согласовать порядок работы до публикации задач в трекере. Claude Code 711 230установок

Вопросы о router-core

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

Выполни npx skills add TanStack/router --skill router-core -a claude-code. Файл скилла окажется по пути ~/.claude/skills/router-core/SKILL.md.

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

Это точка входа в набор скиллов по TanStack Router. Она подсказывает агенту, какой подскилл открыть под конкретную задачу, и фиксирует общие правила: типы выводятся, лоадеры клиентские.

Скилл подойдёт для проекта на Next.js или React Router?

Нет, он про TanStack Router. Лоадеры здесь по умолчанию работают на клиенте, а не на сервере, как в Next.js или Remix, и API между этими роутерами переносить нельзя.

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

SKILL.md · MIT
---
name: router-core
description: >-
  Framework-agnostic core concepts for TanStack Router: route trees,
  createRouter, createRoute, createRootRoute, createRootRouteWithContext,
  addChildren, Register type declaration, route matching, route sorting,
  file naming conventions. Entry point for all router skills.
metadata:
  type: core
  library: tanstack-router
  library_version: '1.171.15'
---

# TanStack Router Core

TanStack Router is a type-safe router for React and Solid with built-in SWR caching, JSON-first search params, file-based route generation, and end-to-end type inference. The core is framework-agnostic; React and Solid bindings layer on top.

> **CRITICAL**: TanStack Router types are FULLY INFERRED. Never cast, never annotate inferred values. This is the #1 AI agent mistake.

> **CRITICAL**: TanStack Router is CLIENT-FIRST. Loaders run on the client by default, NOT server-only like Remix/Next.js. Do not confuse TanStack Router APIs with Next.js or React Router.

Use this entry skill to choose one primary sub-skill. Do not load the full catalog. Load a second sub-skill only when the task crosses a real boundary, such as an authenticated loader that needs both `auth-and-guards` and `data-loading`.

## Sub-Skills

| Task                                               | Sub-Skill                                                                    |
| -------------------------------------------------- | ---------------------------------------------------------------------------- |
| Validate, read, write, transform search params     | [router-core/search-params/SKILL.md](./search-params/SKILL.md)               |
| Dynamic segments, splats, optional params          | [router-core/path-params/SKILL.md](./path-params/SKILL.md)                   |
| Link, useNavigate, preloading, blocking            | [router-core/navigation/SKILL.md](./navigation/SKILL.md)                     |
| Route loaders, SWR caching, context, deferred data | [router-core/data-loading/SKILL.md](./data-loading/SKILL.md)                 |
| Auth guards, RBAC, beforeLoad redirects            | [router-core/auth-and-guards/SKILL.md](./auth-and-guards/SKILL.md)           |
| Automatic and manual code splitting                | [router-core/code-splitting/SKILL.md](./code-splitting/SKILL.md)             |
| 404 handling, error boundaries, notFound()         | [router-core/not-found-and-errors/SKILL.md](./not-found-and-errors/SKILL.md) |
| Inference, Register, from narrowing, TS perf       | [router-core/type-safety/SKILL.md](./type-safety/SKILL.md)                   |
| Streaming/non-streaming SSR, hydration, head mgmt  | [router-core/ssr/SKILL.md](./ssr/SKILL.md)                                   |

## Quick Decision Tree

```
Need to add/read/write URL query parameters?
  → router-core/search-params

Need dynamic URL segments like /posts/$postId?
  → router-core/path-params

Need to create links or navigate programmatically?
  → router-core/navigation

Need to fetch data for a route?
  Is it client-side only or client+server?
    → router-core/data-loading
  Using TanStack Query as external cache?
    → compositions/router-query (separate skill)

Need to protect routes behind auth?
  → router-core/auth-and-guards

Need to reduce bundle size per route?
  → router-core/code-splitting

Need custom 404 or error handling?
  → router-core/not-found-and-errors

Having TypeScript issues or performance problems?
  → router-core/type-safety

Need server-side rendering?
  → router-core/ssr
```

## Cross-Cutting Completion Checks

For route refactors:

1. Rename or move the route file; do not hand-edit the generated `createFileRoute` path.
2. Regenerate `routeTree.gen.ts` with the configured Router plugin or CLI.
3. Update links, redirects, `from` narrowing, params, and tests that reference the old route.
4. Run type tests and a production build. A typecheck alone does not prove route generation or bundling works.

For response schema changes:

1. Update the source model and shared validation schema.
2. Update the server function or API serializer so the field exists at runtime.
3. Update loader and component consumers without casts.
4. Assert the actual response payload in a unit or integration test. Typechecking cannot catch a serializer that omits the new field.

## Minimal Working Example

```tsx
// src/routes/__root.tsx
import { createRootRoute, Outlet } from '@tanstack/react-router'

export const Route = createRootRoute({
  component: () => <Outlet />,
})
```

```tsx
// src/routes/index.tsx
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/')({
  component: () => <h1>Home</h1>,
})
```

```tsx
// src/router.tsx
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'

const router = createRouter({ routeTree })

// REQUIRED for type safety — without this, Link/useNavigate have no autocomplete
declare module '@tanstack/react-router' {
  interface Register {
    router: typeof router
  }
}

export default router
```

```tsx
// src/main.tsx
import { RouterProvider } from '@tanstack/react-router'
import router from './router'

function App() {
  return <RouterProvider router={router} />
}
```

## Common Mistakes

### HIGH: createFileRoute path string must match the file path

The Vite plugin manages the path string in `createFileRoute`. Do not change it manually — it must match the file's location under `src/routes/`:

```tsx
// File: src/routes/posts/$postId.tsx
export const Route = createFileRoute('/posts/$postId')({
  // ✅ matches file path
  component: PostPage,
})

export const Route = createFileRoute('/post/$postId')({
  // ❌ silent mismatch
  component: PostPage,
})
```

The plugin auto-generates this string. If you rename a route file, the plugin updates it. Never edit the path string by hand.

## Version Note

This skill targets `@tanstack/router-core` v1.171.15. Splat routes use `$` (not `*`); the `*` compat alias will be removed in v2.

© TanStack · MIT · TanStack/router

Смотрите также

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

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