Sub topic 8
Path mapping with paths and baseUrl
This chapter assumes you can run tsc, edit tsconfig.json, and read a relative import such as ./math.js. It also assumes you know the module and moduleResolution options from the earlier chapters. Path mapping is a compile-time feature of module resolution. It changes where TypeScript looks for a file. It does not change the JavaScript that runs.
Why path mapping exists
Deep relative imports are hard to read and break when you move a file:
import { formatDate } from "../../../utils/date.js";Path mapping lets you write an alias that stays the same wherever the importing file lives:
import { formatDate } from "@utils/date.js";The compiler needs a rule that turns @utils/date.js into a real file. The baseUrl and paths options in compilerOptions provide that rule.
The paths option
paths maps an import specifier pattern to a list of candidate locations. Each pattern may contain at most one * wildcard. The text matched by * in the import is substituted into the * of each candidate.
{
"compilerOptions": {
"module": "nodenext",
"strict": true,
"outDir": "dist",
"paths": {
"@utils/*": ["./src/utils/*"],
"@config": ["./src/config/index.ts"]
}
},
"include": ["src"]
}With this configuration:
| Import specifier | Pattern matched | Candidate path tried |
|---|---|---|
| `@utils/date` | `@utils/*` | `./src/utils/date` |
| `@utils/strings/trim` | `@utils/*` | `./src/utils/strings/trim` |
| `@config` | `@config` | `./src/config/index.ts` |
The candidate path is then resolved with the usual rules: TypeScript tries file extensions and, depending on the resolution mode, index files in directories. A pattern without * matches only the exact specifier.
Candidates are tried in order. If the first does not exist, the next is tried. This is useful for overlaying generated code on top of source code:
{
"compilerOptions": {
"paths": {
"@gen/*": ["./generated/*", "./src/fallback/*"]
}
}
}If several patterns match an import, TypeScript uses the one with the longest prefix before the *. A pattern with no wildcard that matches exactly wins over any wildcard pattern.
Where paths are relative to
Paths in paths are resolved relative to the tsconfig.json file that defines them. This applies when baseUrl is not set. Older guides say you must set baseUrl to use paths. That has not been required since TypeScript 4.1. Entries starting with ./ are anchored to the config file.
When baseUrl is set, paths entries are resolved relative to baseUrl instead. The config file's own location no longer matters for them.
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@utils/*": ["utils/*"]
}
}
}Here @utils/date resolves to ./src/utils/date, because utils/* is taken relative to ./src.
The baseUrl option
baseUrl does two things.
- It anchors
pathsentries, as shown above. - It lets you write non-relative imports that resolve from that directory.
With "baseUrl": "./src", this import works with no paths entry:
import { formatDate } from "utils/date";TypeScript checks ./src/utils/date first and falls back to node_modules if nothing is found there.
The second behavior is a common source of trouble. A bare specifier like utils/date looks identical to an npm package name. If you later install a package named utils, or a folder in src shares a name with a package, the meaning of the import depends on which lookup wins. Because of this risk, many teams avoid baseUrl as a resolution root. They set only paths with explicit alias prefixes such as @utils/* or #utils/*.
placeholderThe callout below summarizes the recommendation.
How resolution proceeds
For a non-relative specifier, the compiler tries these steps in order.
Relative specifiers such as ./date.js skip paths entirely. Path mapping applies only to non-relative specifiers.
The runtime does not know about paths
This is the most important edge case. TypeScript uses paths to type-check, but tsc does not rewrite import specifiers in the emitted JavaScript. Given this source:
import { formatDate } from "@utils/date.js";
console.log(formatDate(new Date(0)));the emitted dist/main.js still contains from "@utils/date.js". Node.js has no idea what @utils means and fails at startup with an ERR_MODULE_NOT_FOUND error, or a Cannot find module error under CommonJS.
The code type-checks cleanly and still crashes. You must make the runtime or build tool understand the same alias. The options are listed below.
| Environment | How to teach it the alias |
|---|---|
| Bundler (Vite, webpack, esbuild) | Configure the bundler's alias setting or use a plugin that reads `tsconfig.json` paths |
| Jest | Set `moduleNameMapper` to mirror `paths` |
| Node.js directly | Use package `imports` (a `#`-prefixed alias in `package.json`), or a loader or post-build rewrite step |
| Deno or Bun | Bun reads `tsconfig.json` paths itself. Deno uses an import map |
For Node.js, the imports field in package.json is the standard way to define aliases. Names must start with #.
{
"name": "my-app",
"type": "module",
"imports": {
"#utils/*": "./dist/utils/*"
}
}TypeScript understands imports when moduleResolution is node16, nodenext, or bundler. Pointing the target at dist means Node.js finds the compiled file at run time. TypeScript can map a dist target back to the matching source file when outDir and rootDir are set, so you often need no separate paths entry. This keeps one source of truth for both compiler and runtime.
Common errors
- TS2307: Cannot find module '@utils/date'. Check that the pattern matches the specifier, that the candidate path is correct relative to the config file (or
baseUrl), and thatincludecovers the target file. - Works in the editor, fails in the test runner. The editor reads
tsconfig.json. The test runner needs its own mapping, such as Jest'smoduleNameMapper. - Aliases missing from declaration files. With
declarationon,tsccopies import specifiers into.d.tsoutput unchanged. A consumer of your published package cannot resolve@utils/date, because yourpathsconfig does not travel with the package. Avoid aliases in code that appears in public types, or bundle and rewrite the declarations. - Extension mismatch. Under
nodenext, the specifier in source must include the.jsextension, even in an alias.@utils/datewithout an extension fails for ES module files. - Config inheritance surprises. If a config uses
extends,pathsreplaces the parent'spathsentirely. It does not merge. Relative candidates resolve against the config file where they were written, which is usually what you want. - Multiple wildcards. A pattern with two
*characters is an error.
A worked example
Take this layout:
project/
tsconfig.json
package.json
src/
main.ts
utils/
date.tssrc/utils/date.ts:
export function formatDate(d: Date): string {
return d.toISOString().slice(0, 10);
}src/main.ts:
import { formatDate } from "#utils/date.js";
console.log(formatDate(new Date(0)));package.json:
{
"name": "my-app",
"type": "module",
"imports": {
"#utils/*": "./dist/utils/*"
}
}tsconfig.json:
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"strict": true,
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}Running npx tsc and then node dist/main.js prints 1970-01-01. Both the compiler and Node.js agree on what #utils/date.js means, so no extra tooling is needed. If you replaced the imports approach with a paths entry, tsc would still pass but node dist/main.js would fail until you added a bundler or loader.
Choosing an approach
| Situation | Suggested setup |
|---|---|
| App built with a bundler | `paths` in `tsconfig.json`, mirrored in the bundler alias or via a plugin |
| Node.js app run directly | `imports` in `package.json` with `#` aliases |
| Published library | Relative imports inside the source, so emitted `.js` and `.d.ts` files work for every consumer |
| Legacy project with `baseUrl` | Keep it, but add a prefix convention so local names do not clash with packages |
Exercise
A project sets "paths": { "@lib/*": ["./src/lib/*"] } and no baseUrl. The code import { x } from "@lib/x.js" compiles with no errors, but node dist/main.js fails with a module-not-found error. Why does this happen, and what is one fix that needs no extra build tooling?
Show answer
tsc uses paths only to find types and does not rewrite the specifier, so dist/main.js still imports @lib/x.js, which Node.js cannot resolve. A fix without extra tooling is to define "imports": { "#lib/*": "./dist/lib/*" } in package.json and change the import to #lib/x.js. Node.js and TypeScript (with nodenext) both understand that alias.
Exercise
With "baseUrl": "./src" and "paths": { "@ui/*": ["components/*"] }, which file does import { Button } from "@ui/button" resolve to first?
Show answer
./src/components/button, with the usual extension lookup. The paths candidate components/* is relative to baseUrl, so * is replaced by button and the result is placed under ./src.