Warning
只有在您没有使用受支持的打包器时才应该使用 TanStack Router CLI。CLI 仅支持生成路由树文件,不提供任何其他功能。
要在 TanStack Router CLI 中使用基于文件的路由,您需要安装 @tanstack/router-cli 包。
npm install -D @tanstack/router-cli
npm install -D @tanstack/router-cli
安装完成后,您需要修改 package.json 中的脚本,以便 CLI 可以 watch 和 generate 文件。
{
"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 && ..."
}
}
您不应该忘记_忽略_生成的路由树文件。前往忽略生成的路由树文件部分了解更多信息。
安装 CLI 后,可以通过 tsr 命令使用以下命令
根据提供的配置为项目生成路由。
tsr generate
tsr generate
持续监视指定目录并根据需要重新生成路由。
用法:
tsr watch
tsr watch
启用基于文件的路由后,每当您在开发模式下启动应用程序时,TanStack Router 将监视您配置的 routesDirectory 并在添加、删除或更改文件时生成您的路由树。
如果您的项目配置为使用 linter 和/或格式化程序,您可能希望忽略生成的路由树文件。此文件由 TanStack Router 管理,因此不应被您的 linter 或格式化程序更改。
以下是一些帮助您忽略生成的路由树文件的资源:
Warning
如果您使用 VSCode,在重命名路由后可能会遇到路由树文件意外打开(带有错误)的情况。
您可以通过在 VSCode 设置中将文件标记为只读来防止这种情况。我们建议还使用以下设置将其从搜索结果和文件监视器中排除:
{
"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 进行基于文件的路由时,它带有一些合理的默认值,应该适用于大多数项目:
{
"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 参考中找到所有可用的配置选项。