Avatar ·

如何为 TypeScript 配置 tsconfig.json 中的路径别名?

你好!我是 TypeScript 新手,正在尝试组织项目结构。我有一个简单的文件夹结构: ``` src/ ├── components/ │ └── Header.ts ├── utils/ │ └── helpers.ts └── index.ts ``` 在 `index.ts` 文件中,我这样导入组件和工具: ```typescript import { Header } from './components/Header'; import { formatDate } from './utils/helpers'; ``` 一切正常,但当项目扩大时,相对路径会变得非常长且不方便,例如:`../../components/Header` 或 `../../../utils/helpers`。这看起来很糟糕且难以维护。 我听说可以在 `tsconfig.json` 中配置路径别名(path aliases),以便像 `@components/Header` 或 `@utils/helpers` 这样编写导入。我尝试在 `tsconfig.json` 中添加了以下配置: ```json { "compilerOptions": { "baseUrl": ".", "paths": { "@components/*": ["src/components/*"], "@utils/*": ["src/utils/*"] } } } ``` 但当我尝试编写