Capítulo 34 de 57
TanStack Router splits each route into critical configuration (path parsing, search validation, loaders, context) that must be available immediately, and non-critical configuration (component, errorComponent, pendingComponent, notFoundComponent) that can be loaded on demand, either automatically or via the .lazy.tsx file suffix.
autoCodeSplitting: true in the tanstackRouter Vite plugin options. Only works with file-based routing and a supported bundler, not with the CLI alone..lazy.tsx suffix: manual code-splitting approach; move non-critical exports into a sibling file named <route>.lazy.tsx and use createLazyFileRoute instead of createFileRoute..lazy.tsx file, delete the original file entirely; TanStack Router generates a virtual route anchor in the route tree automatically.posts.tsx can be moved into posts/route.tsx to group a route's files (route, lazy, loader) into one directory.Route.lazy() / createLazyRoute: code-based routing equivalent of .lazy.tsx, splitting a route's component into a separate imported file.lazyFn: loaders can also be split out using lazyFn(() => import('./loader'), 'loader'), though this is discouraged because it adds an extra async round-trip before data fetching starts.getRouteApi: helper to access a route's type-safe hooks (useLoaderData, useLoaderDeps, useMatch, useParams, useRouteContext, useSearch) from a separate file without importing the Route object directly, avoiding circular dependencies.// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { tanstackRouter } from '@tanstack/router-plugin/vite'
export default defineConfig({
plugins: [
tanstackRouter({ autoCodeSplitting: true }),
react(), // must come after the TanStack Router plugin
],
})
// src/routes/posts.tsx (critical)
export const Route = createFileRoute('/posts')({
loader: fetchPosts,
})
// src/routes/posts.lazy.tsx (non-critical)
import { createLazyFileRoute } from '@tanstack/react-router'
export const Route = createLazyFileRoute('/posts')({
component: Posts,
})
function Posts() { /* ... */ }
.lazy.tsx, separating loader (critical) from component (non-critical).autoCodeSplitting: true over manual .lazy.tsx files when using a supported bundler; it requires no restructuring.__root.tsx) cannot be code-split since it always renders.getRouteApi instead of importing the Route object in split component files to avoid circular imports.codeSplitGroupings, splitBehavior, defaultBehavior) for this same feature.