字
字节笔记本
2026年5月3日
TanStack Start - 路径别名 (Path Aliases)
API中转
¥120
使用 TypeScript 路径别名简化导入语句。路径别名允许你为项目中较远的目录路径定义快捷方式,避免过长的相对导入。
基本配置
1. 更新 tsconfig.json
json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*": ["./src/*"]
}
}
}2. 安装 Vite 插件
bash
npm install -D vite-tsconfig-paths3. 更新 vite.config.ts
tsx
import viteTsConfigPaths from 'vite-tsconfig-paths'
export default defineConfig({
plugins: [
tanstackStart(),
viteReact(),
viteTsConfigPaths({
projects: ['./tsconfig.json'],
}),
],
})使用示例
tsx
// ✅ 使用路径别名(推荐)
import { Input } from '~/components/ui/input'
import { Button } from '~/components/ui/button'
import { useUser } from '~/hooks/useUser'
// ❌ 使用相对路径(不推荐)
import { Input } from '../../../components/ui/input'
import { Button } from '../../../components/ui/button'
import { useUser } from '../../../hooks/useUser'多个路径别名
json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*": ["./src/*"],
"@/*": ["./src/*"],
"@/components/*": ["./src/components/*"],
"@/lib/*": ["./src/lib/*"],
"@/hooks/*": ["./src/hooks/*"],
"@/utils/*": ["./src/utils/*"],
"@/styles/*": ["./src/styles/*"],
"@/types/*": ["./src/types/*"]
}
}
}对比
| 方面 | 相对导入 | 路径别名 |
|---|---|---|
| 简洁性 | 冗长 | 简洁 |
| 可维护性 | 难以重构 | 易于维护 |
| 可读性 | 难以理解 | 清晰明了 |
| 移动文件 | 需要更新所有导入 | 无需更改 |
| 配置 | 无需配置 | 需要配置 |
常见问题
- 路径别名不工作:确保安装了
vite-tsconfig-paths,vite.config.ts中包含插件配置 - TypeScript 报错:确保
tsconfig.json中配置正确,baseUrl已设置 - Monorepo:在
viteTsConfigPaths的projects数组中添加多个 tsconfig 路径
分享: