框架
版本

使用 Router CLI 安装

警告

仅当您未使用受支持的打包工具时才应使用 TanStack Router CLI。CLI 仅支持生成路由树文件,不提供任何其他功能。

要将文件路由与 TanStack Router CLI 一起使用,您需要安装 @tanstack/router-cli 包。

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

安装后,您需要修改 package.json 中的脚本,以便 CLI 监视生成文件。

json
{
  "scripts": {
    "generate-routes": "tsr generate",
    "watch-routes": "tsr watch",
    "build": "npm run generate-routes && ...",
    "dev": "npm run watch-routes && ..."
  }
}
{
  "scripts": {
    "generate-routes": "tsr generate",
    "watch-routes": "tsr watch",
    "build": "npm run generate-routes && ...",
    "dev": "npm run watch-routes && ..."
  }
}

您不应该忘记**忽略**生成的路由树文件。请参阅[忽略生成的路由树文件](#ignoring-the-generated-route-tree-file)部分以了解更多信息。

安装 CLI 后,可以通过 tsr 命令使用以下命令

使用 generate 命令

根据提供的配置为项目生成路由。

sh
tsr generate
tsr generate

使用 watch 命令

持续监视指定的目录并根据需要重新生成路由。

用法

sh
tsr watch
tsr watch

启用文件路由后,每当您在开发模式下启动应用程序时,TanStack Router 将监视您配置的 routesDirectory 并在添加、删除或更改文件时生成您的路由树。

忽略生成的路由树文件

如果您的项目配置了 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 CLI 进行文件路由时,它带有一些合理的默认值,应该适用于大多数项目

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

如果这些默认值适用于您的项目,您根本不需要配置任何东西!但是,如果您需要自定义配置,可以通过在项目目录的根目录中创建 tsr.config.json 文件来实现。

您可以在[文件路由 API 参考](/router/latest/docs/api/file-based-routing)中找到所有可用的配置选项。

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

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

Bytes

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

订阅 Bytes

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

Bytes

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