使用 Vite 安装

要在 Vite 中使用基于文件的路由,您需要安装 @tanstack/router-plugin 包。

sh
npm install -D @tanstack/router-plugin
npm install -D @tanstack/router-plugin

安装完成后,您需要将插件添加到 Vite 配置中。

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    tanstackRouter({
      target: 'solid',
      autoCodeSplitting: true,
    }),
    solid(),
    // ...
  ],
})
// vite.config.ts
import { defineConfig } from 'vite'
import solid from 'vite-plugin-solid'
import { tanstackRouter } from '@tanstack/router-plugin/vite'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    tanstackRouter({
      target: 'solid',
      autoCodeSplitting: true,
    }),
    solid(),
    // ...
  ],
})

如果您使用 TypeScript,还应该将以下选项添加到 tsconfig.json 中:

json
{
  "compilerOptions": {
    "jsx": "preserve",
    "jsxImportSource": "solid-js"
  }
}
{
  "compilerOptions": {
    "jsx": "preserve",
    "jsxImportSource": "solid-js"
  }
}

或者,您可以克隆我们的快速开始 Vite 示例并开始使用。

现在您已经将插件添加到 Vite 配置中,您就可以开始使用 TanStack Router 的基于文件的路由了。

忽略生成的路由树文件

如果您的项目配置为使用 linter 和/或格式化程序,您可能希望忽略生成的路由树文件。此文件由 TanStack Router 管理,因此不应被您的 linter 或格式化程序更改。

以下是一些帮助您忽略生成的路由树文件的资源:

Warning

如果您使用 VSCode,在重命名路由后可能会遇到路由树文件意外打开(带有错误)的情况。

您可以通过在 VSCode 设置中将文件标记为只读来防止这种情况。我们建议还使用以下设置将其从搜索结果和文件监视器中排除:

json
{
  "files.readonlyInclude": {
    "**/routeTree.gen.ts": true
  },
  "files.watcherExclude": {
    "**/routeTree.gen.ts": true
  },
  "search.exclude": {
    "**/routeTree.gen.ts": true
  }
}
{
  "files.readonlyInclude": {
    "**/routeTree.gen.ts": true
  },
  "files.watcherExclude": {
    "**/routeTree.gen.ts": true
  },
  "search.exclude": {
    "**/routeTree.gen.ts": true
  }
}

您可以在用户级别使用这些设置,也可以通过在项目根目录创建 .vscode/settings.json 文件仅为单个工作区使用这些设置。

配置

当使用 TanStack Router 插件与 Vite 进行基于文件的路由时,它带有一些合理的默认值,应该适用于大多数项目:

json
{
  "routesDirectory": "./src/routes",
  "generatedRouteTree": "./src/routeTree.gen.ts",
  "routeFileIgnorePrefix": "-",
  "quoteStyle": "single"
}
{
  "routesDirectory": "./src/routes",
  "generatedRouteTree": "./src/routeTree.gen.ts",
  "routeFileIgnorePrefix": "-",
  "quoteStyle": "single"
}

如果这些默认值适用于您的项目,您完全不需要配置任何东西!但是,如果您需要自定义配置,可以通过编辑传递给 tanstackRouter 函数的配置对象来实现。

您可以在基于文件的路由 API 参考中找到所有可用的配置选项。