Capítulo 8 de 57

Chapter 8: With Vite

Core Idea

File-based routing under Vite requires installing @tanstack/router-plugin and adding the tanstackRouter plugin (from @tanstack/router-plugin/vite) to Vite's config before the framework plugin, after which the generated routeTree.gen.ts file should be excluded from linters, formatters, and VSCode's file watcher/search.

Key Concepts

  • @tanstack/router-plugin: The dev dependency that provides bundler-specific plugin entry points (/vite, /rspack, /webpack, /esbuild).
  • Plugin ordering: tanstackRouter({ target: 'react', autoCodeSplitting: true }) must appear before react() (or solid()) in the plugins array.
  • autoCodeSplitting: true: Enables automatic code-splitting of route components without manual lazyRouteComponent wiring.
  • Default configuration: routesDirectory: "./src/routes", generatedRouteTree: "./src/routeTree.gen.ts", routeFileIgnorePrefix: "-", quoteStyle: "single", sane defaults that most projects never need to override.
  • Ignoring the generated file: Recommended to add routeTree.gen.ts to .prettierignore, ESLint ignore config, and Biome's files.ignore, since the file is managed by the router and shouldn't be reformatted or linted.
  • VSCode readonly settings: Marking **/routeTree.gen.ts as files.readonlyInclude, plus excluding it from files.watcherExclude and search.exclude, prevents VSCode from unexpectedly opening the file with errors after a route rename.

Code Examples

// 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({
      target: 'react',
      autoCodeSplitting: true,
    }),
    react(),
  ],
})
  • What it demonstrates: Minimal Vite configuration enabling file-based routing with automatic code splitting.

Key Takeaways

  1. Always place tanstackRouter(...) before the React/Solid plugin in Vite's plugins array, wrong order can break route generation.
  2. Enable autoCodeSplitting: true by default, it removes the need for manual lazyRouteComponent calls per route.
  3. Configure editor/linter/formatter ignore rules for routeTree.gen.ts immediately after setup to avoid noisy diffs and VSCode errors.

Connects To

  • Ch 7: Manual Installation shows the full app scaffold this Vite plugin config plugs into.
  • Ch 9-11: Rspack, Webpack, and Esbuild chapters cover the same plugin (@tanstack/router-plugin) for other bundlers, with the identical default configuration and ignore-file guidance.
  • Ch 12: With Router CLI is the fallback for bundlers not covered here.