tsconfig Path Aliases dan Project References TypeScript
Definisi
tsconfig.json mendukung paths (alias impor seperti @/components) dan project references (references + composite) untuk membagi codebase besar jadi sub-project yang di-build terpisah namun tetap terhubung type.
Kapan dipakai
- paths: hindari impor relatif
../../berantakan; pakai@/di app. - project references: monorepo dengan beberapa package (
core,web,api) yang butuh type-check cepat & build bertahap. - Jangan pakai references untuk project kecil — cukup
paths.
Cara kerja
Alias
// tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": { "@/*": ["src/*"] }
}
}import { Button } from '@/components/Button'; // bukan ../../../componentsReferences
// tsconfig.json (root)
{ "files": [], "references": [{ "path": "./packages/core" }, { "path": "./packages/web" }] }tsc -b # build semua referencesStruktur alur
Loading diagram...
Catatan implementasi
pathsbutuh dukungan bundler (Vite/Webpack alias) — TS hanya cek tipe, bukan resolve runtime.- Project references butuh
"composite": truedi tiap sub-tsconfig. tsc -b(build mode) menghormati dependency graph; lebih cepat daritscpenuh.- Untuk Vite, alias di
vite.config(resolve.alias) terpisah dari TS.
Kesalahan umum
- paths di TS tapi bundler tidak: runtime error "module not found".
- Lupa composite: references gagal build.
- Alias terlalu dalam:
@/tetap perlu konsisten antar tool. - tsc bukan tsc -b: references tidak di-build bertahap.