服务器与执行
路径别名(Path Aliases)
路径别名(Path Aliases)是 TypeScript 的一个实用特性,允许你为项目中相隔较远的路径定义一个快捷方式。它可以帮助你避免代码里冗长的相对导入,也让重构项目结构更容易。
默认情况下,TanStack Start 不自带路径别名。但你可以很容易地在项目根目录的 tsconfig.json 中添加以下配置来启用它:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*": ["./src/*"]
}
}
}在这个例子中,我们定义了路径别名 ~/*,映射到 ./src/* 目录。这意味着你现在可以用 ~ 前缀从 src 目录导入文件。
更新完 tsconfig.json 之后,还要配置你的构建工具,让它解析相同的路径别名。
Vite 8
Vite 8+ 内置了对路径别名的支持,默认关闭。要启用它,只需在 vite.config.ts 中添加以下配置:
// vite.config.ts
import { defineConfig } from 'vite'
export default defineConfig({
resolve: {
// This enables built-in support for path aliases defined in tsconfig.json
tsconfigPaths: true,
},
})Vite 7 及更早版本
对于 Vite 7 及更早版本,安装 vite-tsconfig-paths 插件来启用 TanStack Start 项目中的路径别名。运行下面的命令:
npm install -D vite-tsconfig-paths然后需要更新 vite.config.ts 文件,加入以下内容:
// vite.config.ts
import { defineConfig } from 'vite'
import viteTsConfigPaths from 'vite-tsconfig-paths'
export default defineConfig({
plugins: [
// this is the plugin that enables path aliases
viteTsConfigPaths({
projects: ['./tsconfig.json'],
}),
],
})配置完成后,你就能用路径别名导入文件了:
// app/routes/posts/$postId/edit.tsx
import { Input } from '~/components/ui/input'
// instead of
import { Input } from '../../../components/ui/input'