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://vite.ac.cn/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://vite.ac.cn/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 和/或 formatter,您可能希望忽略生成的路由树文件。此文件由 TanStack Router 管理,因此不应由您的 linter 或 formatter 更改。

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

警告

如果您正在使用 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 Plugin 与 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 参考](/router/latest/docs/api/file-based-routing)中找到所有可用的配置选项。

我们的合作伙伴
Code Rabbit
Netlify
Neon
Clerk
Convex
Sentry
订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。

订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。