Path mapping
- TypeScript course
- Expert
- Lesson 16/35
- 4 min
Learn module mapping with paths.
What is path mapping?
paths maps import specifiers to real file paths, so you can use short aliases instead of long relative paths. The baseUrl field sets the root for paths entries and is usually set to ..
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@lib/*": ["lib/*"]
}
}
}Here @/utils resolves to src/utils.
Alias resolution
An alias contains a * wildcard; during resolution the left of the wildcard matches and the right is substituted. For example "@/*": ["src/*"] turns @/utils/helpers into src/utils/helpers.
const paths = { "@/*": ["src/*"] };
// "@/utils" → "src/utils"If there are multiple targets, the first match is used.
Practice Resolve the alias
Write a resolveAlias function taking specifier and paths. For each alias, strip the * and match the prefix; on match, replace the target's * with the remainder and return it. For paths = { "@/*": ["src/*"] }, print the result of resolveAlias("@/utils", paths).
Starter code
// resolveAlias: alias'ı gerçek yola çevirir
// her alias'taki *'i çıkarıp önek eşleşmesi yap
// eşleşirse hedefte *'i kalanla değiştir
// "@/utils" ve { "@/*": ["src/*"] } için sonucu yazdırSample solution
function resolveAlias(specifier: string, paths: Record<string, string[]>): string {
for (const [alias, targets] of Object.entries(paths)) {
const prefix = alias.replace("*", "");
if (specifier.startsWith(prefix)) {
const rest = specifier.slice(prefix.length);
return targets[0].replace("*", "") + rest;
}
}
return specifier;
}
const paths = { "@/*": ["src/*"] };
console.log(resolveAlias("@/utils", paths));Expected output
src/utils
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which field sets the root directory when using `paths`?
- baseUrl Correct answer
- outDir
- baseDir
- rootDir
Explanation: baseUrl sets the root against which paths entries are resolved; rootDir is the input root, outDir is the output directory, and baseDir is not a valid option.
2 Define an alias
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["____/*"]
}
}
}
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
Explanation: The alias target should be the source root directory; dist is output, lib is optional, and node_modules is the dependency directory, none of which fit as an alias target.
3 Path mapping parts
| Term | Meaning |
|---|---|
paths |
lists alias mappings |
baseUrl |
sets resolution root |
* |
wildcard |
@/* |
example alias pattern |