模块与配置
路径别名与项目引用
配置 paths 别名、references 项目引用、monorepo 类型共享
路径别名与项目引用
大型项目中正确配置路径别名和项目引用,提升开发效率。
学完本章你将: 配置 paths 别名、项目引用、monorepo 管理。
路径别名配置
json
// tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@components/*": ["src/components/*"],
"@utils/*": ["src/utils/*"],
"@types/*": ["src/types/*"]
}
}
}
typescript
// 使用别名代替 ../../../ 相对路径
import { Button } from "@components/Button";
import { formatDate } from "@utils/date";
import type { User } from "@types/models";
配合打包工具
javascript
// vite.config.ts 也需要配置
export default defineConfig({
resolve: {
alias: {
"@": "/src",
},
},
});
// next.config.ts
const config = {
// Next.js 自动读取 tsconfig paths
};
项目引用
monorepo/
├── tsconfig.json // 根配置
├── packages/
│ ├── core/
│ │ ├── tsconfig.json
│ │ └── src/
│ ├── web/
│ │ ├── tsconfig.json
│ │ └── src/
│ └── mobile/
│ ├── tsconfig.json
│ └── src/
json
// 根 tsconfig.json
{
"files": [],
"references": [
{ "path": "./packages/core" },
{ "path": "./packages/web" },
{ "path": "./packages/mobile" }
]
}
// packages/core/tsconfig.json
{
"compilerOptions": {
"composite": true,
"declaration": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src"]
}
命令
bash
# 构建所有引用项目
tsc --build
# 增量构建(只编译变更)
tsc --build --incremental
# 清理构建产物
tsc --build --clean