ByteNoteByteNote

字节笔记本

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-paths

3. 更新 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-pathsvite.config.ts 中包含插件配置
  • TypeScript 报错:确保 tsconfig.json 中配置正确,baseUrl 已设置
  • Monorepo:在 viteTsConfigPathsprojects 数组中添加多个 tsconfig 路径
分享: