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

code-splitting — скилл для Claude Code: ленивая загрузка компонентов маршрутов

Скилл code-splitting разделяет код маршрутов TanStack Router на критичную и ленивую части: автоматически создаёт отдельные чанки или позволяет настроить разделение вручную.

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

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

Что делает code-splitting

TanStack Router различает две части кода маршрута: критичную (парсинг пути, validateSearch, loader, контекст) и ленивую (компоненты, errorComponent, pendingComponent). Скилл включает автоматическое разделение (autoCodeSplitting: true) в плагин Vite, так что вся логика хранится в одном файле routes/posts.tsx, а компоненты автоматически выделяются в отдельный чанк.

Для CLI-приложений без плагина bundler'а работает ручное разделение: критичная часть в routes/posts.tsx, ленивая — в routes/posts.lazy.tsx с помощью createLazyFileRoute. Чтобы типизированные хуки работали в отдельных файлах, используй getRouteApi('/posts') — это даёт доступ к useLoaderData, useParams, useSearch без импорта самого объекта Route, который помешал бы сплиттингу.

Пер-маршрутные переопределения (codeSplitGroupings) позволяют объединить loader и component в один чанк, если отдельная загрузка даёт двойной async-штраф. Глобальная конфигурация defaultBehavior и splitBehavior в vite.config.ts помогают тонко настроить группировку по паттернам маршрутов. КРИТИЧНО: если компонент экспортирован обычной функцией, он попадёт в основной bundle и сплиттинг не сработает.

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

  • Разделить компоненты маршрутов в отдельные чанки без дублирования кода
  • Оставить loader в основном bundle, чтобы маршрут загружался параллельно компоненту
  • Получить типизированные хуки в файле .lazy.tsx без разрушения сплиттинга
  • Переопределить логику сплиттинга для отдельного маршрута или группы маршрутов
  • Настроить автоматический сплиттинг в Vite или сделать ручное разделение для других bundler'ов

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

  • Включи автоматический code-splitting в vite.config.ts: укажи autoCodeSplitting: true в плагине tanstackRouter
  • Используй getRouteApi('/posts') в компоненте из файла posts.lazy.tsx для типизированного доступа к useLoaderData и useParams
  • Объедини loader с компонентом в один чанк через codeSplitGroupings: [['loader', 'component']] в маршруте с тяжёлой логикой

Как установить code-splitting

1Через Skills CLI (Vercel)

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

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

~/.claude/skills/code-splitting/SKILL.md

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

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

Вопросы о code-splitting

Как установить code-splitting в Claude Code?

Выполни npx skills add TanStack/router --skill code-splitting -a claude-code, затем обрати внимание на файл ~/.claude/skills/code-splitting/SKILL.md с полной инструкцией для твоего проекта.

Что делает code-splitting?

Разделяет код маршрутов на части: критичные (config, loader) остаются в основном bundle, ленивые (компоненты) загружаются отдельно. Это уменьшает размер начального bundle и ускоряет первый вывод страницы.

Почему компонент остаётся в основном bundle, если я его экспортировал?

Экспортированные функции-компоненты не сплиттятся — они становятся частью основного bundle автоматически. Оставь компонент как обычную функцию внутри файла маршрута или используй createLazyFileRoute в отдельном .lazy.tsx файле.

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

SKILL.md · MIT
---
name: code-splitting
description: >-
  Automatic code splitting (autoCodeSplitting), .lazy.tsx convention,
  createLazyFileRoute, createLazyRoute, lazyRouteComponent, getRouteApi
  for typed hooks in split files, codeSplitGroupings per-route override,
  splitBehavior programmatic config, critical vs non-critical properties.
metadata:
  type: sub-skill
  library: tanstack-router
  library_version: '1.171.15'
requires:
  - router-core
sources:
  - TanStack/router:docs/router/guide/code-splitting.md
  - TanStack/router:docs/router/guide/automatic-code-splitting.md
---

# Code Splitting

TanStack Router separates route code into **critical** (required to match and start loading) and **non-critical** (can be lazy-loaded). The bundler plugin can split automatically, or you can split manually with `.lazy.tsx` files.

> **CRITICAL**: Never `export` component functions from route files — exported functions are included in the main bundle and bypass code splitting entirely.

> **CRITICAL**: Use `getRouteApi('/path')` in code-split files, NOT `import { Route } from './route'`. Importing Route defeats code splitting.

## What Stays in the Main Bundle (Critical)

- Path parsing/serialization
- `validateSearch`
- `loader`, `beforeLoad`
- Route context, static data
- Links, scripts, styles

## What Gets Split (Non-Critical)

- `component`
- `errorComponent`
- `pendingComponent`
- `notFoundComponent`

> The `loader` is NOT split by default. It is already async, so splitting it adds a double async cost: fetch the chunk, then execute the loader. Only split the loader if you have a specific reason.

## Setup: Automatic Code Splitting

Enable `autoCodeSplitting: true` in the bundler plugin. This is the recommended approach.

```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: [
    // TanStack Router plugin MUST come before the framework plugin
    tanstackRouter({
      autoCodeSplitting: true,
    }),
    react(),
  ],
})
```

With this enabled, route files are automatically transformed. Components are split into separate chunks; loaders stay in the main bundle. No `.lazy.tsx` files needed.

```tsx
// src/routes/posts.tsx — everything in one file, splitting is automatic
import { createFileRoute } from '@tanstack/react-router'
import { fetchPosts } from '../api'

export const Route = createFileRoute('/posts')({
  loader: fetchPosts,
  component: PostsComponent,
})

// NOT exported — this is critical for automatic code splitting to work
function PostsComponent() {
  const posts = Route.useLoaderData()
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  )
}
```

## Manual Splitting with `.lazy.tsx`

If you cannot use automatic code splitting (e.g. CLI-only, no bundler plugin), split manually into two files:

```tsx
// src/routes/posts.tsx — critical route config only
import { createFileRoute } from '@tanstack/react-router'
import { fetchPosts } from '../api'

export const Route = createFileRoute('/posts')({
  loader: fetchPosts,
})
```

```tsx
// src/routes/posts.lazy.tsx — non-critical (lazy-loaded)
import { createLazyFileRoute } from '@tanstack/react-router'

export const Route = createLazyFileRoute('/posts')({
  component: PostsComponent,
})

function PostsComponent() {
  // Use getRouteApi to access typed hooks without importing Route
  return <div>Posts</div>
}
```

`createLazyFileRoute` supports only: `component`, `errorComponent`, `pendingComponent`, `notFoundComponent`.

## Virtual Routes

If splitting leaves the critical route file empty, delete it entirely. A virtual route is auto-generated in `routeTree.gen.ts`:

```tsx
// src/routes/about.lazy.tsx — no about.tsx needed
import { createLazyFileRoute } from '@tanstack/react-router'

export const Route = createLazyFileRoute('/about')({
  component: () => <h1>About Us</h1>,
})
```

## Code-Based Splitting

For code-based (non-file-based) routing, use `createLazyRoute` and the `.lazy()` method:

```tsx
// src/posts.lazy.tsx
import { createLazyRoute } from '@tanstack/react-router'

export const Route = createLazyRoute('/posts')({
  component: PostsComponent,
})

function PostsComponent() {
  return <div>Posts</div>
}
```

```tsx
// src/app.tsx
import { createRoute } from '@tanstack/react-router'

const postsRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/posts',
}).lazy(() => import('./posts.lazy').then((d) => d.Route))
```

## Accessing Typed Hooks in Split Files: `getRouteApi`

When your component lives in a separate file, use `getRouteApi` to get typed access to route hooks without importing the Route object:

```tsx
// src/routes/posts.lazy.tsx
import { createLazyFileRoute, getRouteApi } from '@tanstack/react-router'

const routeApi = getRouteApi('/posts')

export const Route = createLazyFileRoute('/posts')({
  component: PostsComponent,
})

function PostsComponent() {
  const posts = routeApi.useLoaderData()
  const { page } = routeApi.useSearch()
  const params = routeApi.useParams()
  const context = routeApi.useRouteContext()
  return <div>Posts page {page}</div>
}
```

`getRouteApi` provides: `useLoaderData`, `useLoaderDeps`, `useMatch`, `useParams`, `useRouteContext`, `useSearch`.

## Per-Route Split Overrides: `codeSplitGroupings`

Override split behavior for a specific route by adding `codeSplitGroupings` directly in the route file:

```tsx
// src/routes/posts.tsx
import { createFileRoute } from '@tanstack/react-router'
import { loadPostsData } from './-heavy-posts-utils'

export const Route = createFileRoute('/posts')({
  // Bundle loader and component together for this route
  codeSplitGroupings: [['loader', 'component']],
  loader: () => loadPostsData(),
  component: PostsComponent,
})

function PostsComponent() {
  const data = Route.useLoaderData()
  return <div>{data.title}</div>
}
```

## Global Split Configuration

### `defaultBehavior` — Change Default Groupings

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

export default defineConfig({
  plugins: [
    tanstackRouter({
      autoCodeSplitting: true,
      codeSplittingOptions: {
        defaultBehavior: [
          // Bundle all UI components into one chunk
          [
            'component',
            'pendingComponent',
            'errorComponent',
            'notFoundComponent',
          ],
        ],
      },
    }),
  ],
})
```

### `splitBehavior` — Programmatic Per-Route Logic

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

export default defineConfig({
  plugins: [
    tanstackRouter({
      autoCodeSplitting: true,
      codeSplittingOptions: {
        splitBehavior: ({ routeId }) => {
          if (routeId.startsWith('/posts')) {
            return [['loader', 'component']]
          }
          // All other routes use defaultBehavior
        },
      },
    }),
  ],
})
```

### Precedence Order

1. Per-route `codeSplitGroupings` (highest)
2. `splitBehavior` function
3. `defaultBehavior` option (lowest)

## Common Mistakes

### 1. HIGH: Exporting component functions prevents code splitting

```tsx
// WRONG — export puts PostsComponent in the main bundle
export function PostsComponent() {
  return <div>Posts</div>
}

// CORRECT — no export, function stays in the split chunk
function PostsComponent() {
  return <div>Posts</div>
}
```

### 2. MEDIUM: Trying to code-split the root route

`__root.tsx` does not support code splitting. It is always rendered regardless of the current route. Do not create `__root.lazy.tsx`.

### 3. MEDIUM: Splitting the loader adds double async cost

```tsx
// AVOID unless you have a specific reason
codeSplittingOptions: {
  defaultBehavior: [
    ['loader'], // Fetch chunk THEN execute loader = two network waterfalls
    ['component'],
  ],
}

// PREFERRED — loader stays in main bundle (default behavior)
codeSplittingOptions: {
  defaultBehavior: [
    ['component'],
    ['errorComponent'],
    ['notFoundComponent'],
  ],
}
```

### 4. HIGH: Importing Route in code-split files for typed hooks

```tsx
// WRONG — importing Route pulls route config into the lazy chunk
import { Route } from './posts.tsx'
const data = Route.useLoaderData()

// CORRECT — getRouteApi gives typed hooks without pulling in the route
import { getRouteApi } from '@tanstack/react-router'
const routeApi = getRouteApi('/posts')
const data = routeApi.useLoaderData()
```

## Cross-References

- **router-core/data-loading** — Loader splitting decisions affect data loading performance. Splitting the loader adds latency before data can be fetched.
- **router-core/type-safety** — `getRouteApi` is the type-safe way to access hooks from split files.

© TanStack · MIT · TanStack/router

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

Все скиллы по теме «Фронтенд и UI» →
react-vite-best-practices agent-skills Скилл react-vite-best-practices для Claude Code с 23 правилами оптимизации React-приложений на Vite: сборка, code splitting, HMR, ассеты, окружение и анализ бандла. Проверяет компоненты при написании и ревью. CX Codex +1 3 000установок vite-bundle-optimization patterns.dev Скилл vite-bundle-optimization для Claude Code, Codex, Cursor, GitHub Copilot и Gemini CLI обучает агента паттернам оптимизации бандла Vite + React. Активируется при настройке сборки, разбивке кода на чанки или диагностике медленных билдов. CX Codex +1 692установок tanstack-router Claude Skills Maintainers Скилл tanstack-router настраивает типобезопасный роутинг на базе файлов в React и помогает связать его с TanStack Query или Cloudflare Workers. CX Codex +1 468установок react-performance-optimization NickCrew Скилл react-performance-optimization для Claude Code помогает находить узкие места в рендере React, настраивать мемоизацию, разделение кода и виртуализацию списков. Ускоряет медленные экраны и уменьшает бандл. CX Codex +1 1 900установок web-performance-optimization secondsky Скилл web-performance-optimization для Claude Code помогает ускорять загрузку веб-приложений и уменьшать размер сборки. Включается при настройке кэширования и мониторинга Core Web Vitals. CX Codex +1 589установок 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звёзд репо

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

Весь набор →
server-functions Скилл server-functions обучает агента писать типобезопасные RPC-функции через createServerFn в TanStack Start, валидировать входные данные схемами Zod и вызывать их из компонентов. CX Codex +1 221установок auth-and-guards Скилл auth-and-guards для защиты маршрутов в TanStack Router. Перенаправляет неавторизованных пользователей, встраивает проверку ролей и прав, интегрирует Auth0, Clerk, Supabase через контекст роутера. CX Codex +1 219установок navigation Скилл navigation помогает агенту настраивать навигацию в TanStack Router: ссылки, переходы, предзагрузку маршрутов и блокировку ухода со страницы. CX Codex +1 214установок execution-model Скилл execution-model помогает агенту правильно разделять серверный и клиентский код в TanStack Start и учитывать SSR, гидрацию и переменные окружения. CX Codex +1 214установок not-found-and-errors Скилл not-found-and-errors обучает агента настраивать экраны 404 и обработку ошибок в TanStack Router. Помогает пробросить notFound() из loader и оформить запасной UI. CX Codex +1 211установок 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установок

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

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