路径别名

路径别名是 TypeScript 的一个实用功能,它允许你为项目目录结构中可能很远的路径定义快捷方式。这可以帮助你避免代码中冗长的相对导入,并使重构项目结构更加容易。这对于避免代码中冗长的相对导入尤其有用。

默认情况下,TanStack Start 不包含路径别名。但是,你可以通过更新项目根目录中的 tsconfig.json 文件并添加以下配置,轻松地将它们添加到你的项目中

json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~/*": ["./src/*"]
    }
  }
}
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~/*": ["./src/*"]
    }
  }
}

在这个例子中,我们定义了路径别名 ~/*,它映射到 ./src/* 目录。这意味着你现在可以使用 ~ 前缀从 src 目录导入文件。

更新你的 tsconfig.json 文件后,你需要安装 vite-tsconfig-paths 插件,以便在你的 TanStack Start 项目中启用路径别名。你可以通过运行以下命令来做到这一点

sh
npm install -D vite-tsconfig-paths
npm install -D vite-tsconfig-paths

现在,你需要更新你的 app.config.ts 文件以包含以下内容

ts
// app.config.ts
import { defineConfig } from '@tanstack/react-start/config'
import viteTsConfigPaths from 'vite-tsconfig-paths'

export default defineConfig({
  vite: {
    plugins: [
      // this is the plugin that enables path aliases
      viteTsConfigPaths({
        projects: ['./tsconfig.json'],
      }),
    ],
  },
})
// app.config.ts
import { defineConfig } from '@tanstack/react-start/config'
import viteTsConfigPaths from 'vite-tsconfig-paths'

export default defineConfig({
  vite: {
    plugins: [
      // this is the plugin that enables path aliases
      viteTsConfigPaths({
        projects: ['./tsconfig.json'],
      }),
    ],
  },
})

一旦此配置完成,你现在就可以像这样使用路径别名导入文件了

ts
// app/routes/posts/$postId/edit.tsx
import { Input } from '~/components/ui/input'

// instead of

import { Input } from '../../../components/ui/input'
// app/routes/posts/$postId/edit.tsx
import { Input } from '~/components/ui/input'

// instead of

import { Input } from '../../../components/ui/input'
订阅 Bytes

你每周的 JavaScript 新闻。每周一免费发送给超过 100,000 名开发者。

Bytes

没有垃圾邮件。随时取消订阅。