Sub topic 10
paths aliases and their limits
This chapter assumes you can read a tsconfig.json, know how nodenext and bundler resolution differ, and have seen a relative import fail. Earlier chapters covered both modes and the extension rules. Here the question is narrower: what the paths option does, and what it leaves undone.
What paths does
The paths option maps an import specifier to one or more locations. The compiler uses the mapping when it resolves a module, so it can find the file and read its types. A typical setup turns long relative imports into short aliases:
{
"compilerOptions": {
"module": "preserve",
"moduleResolution": "bundler",
"target": "es2022",
"strict": true,
"noEmit": true,
"paths": {
"@app/*": ["./src/*"],
"@config": ["./src/config/index.ts"]
}
}
}With this file, the following imports type-check:
import { formatDate } from "@app/utils/date";
import { config } from "@config";The right-hand paths are relative to the tsconfig.json that contains paths. Since TypeScript 4.1 you no longer need baseUrl for this. Setting baseUrl adds a second behavior you may not want: bare specifiers such as utils/date start resolving against that directory. That makes it easy to import a local folder that shadows a real package. Most projects are better off with paths alone.
The central limit: paths only affects the compiler
paths is a type-checking and resolution aid. The compiler does not rewrite the specifiers in the JavaScript it emits. If you compile import { formatDate } from "@app/utils/date" with tsc, the output still contains "@app/utils/date". Nothing at runtime knows what @app means.
Whether that matters depends on who runs the code:
| Who runs the output | Does the alias work? | What you need |
|---|---|---|
| A bundler (Vite, esbuild, webpack) | Only if the bundler is told about it | The bundler's own alias setting, or a plugin that reads `paths` |
| Node.js directly | No | Avoid the alias, or use `package.json` `imports` |
| A test runner (Jest, Vitest) | Only if configured | A mapping such as `moduleNameMapper` (Jest) or `resolve.alias` (Vitest) |
| A consumer of your published library | No | Never publish aliased specifiers |
The mistake behind most paths bugs is treating the alias as a language feature. It is a hint to the compiler. You must make the same mapping true somewhere else, and you have to keep the two copies in sync.
Pattern rules
paths keys follow a few rules that cause surprises when ignored.
- A key may contain at most one
*. The text matched by the star is substituted into each mapped location that also contains a*. - An exact key without a star matches only that exact specifier.
"@config"does not match"@config/db". - When several keys match, the compiler picks the key with the longest prefix before the
*. - A key can list several locations. The compiler tries them in order and uses the first that resolves. This is a fallback list, and it is not a merge.
{
"compilerOptions": {
"module": "preserve",
"moduleResolution": "bundler",
"noEmit": true,
"paths": {
"@app/*": ["./src/*", "./generated/*"],
"@app/testing/*": ["./test-utils/*"]
}
}
}Here @app/testing/mock uses the second key, because its prefix @app/testing/ is longer than @app/. The specifier @app/user tries ./src/user first and then ./generated/user.
paths under nodenext
paths works with moduleResolution: "nodenext", but the mode's other rules still apply to what you write. In an ES module file, a relative import needs an explicit extension, and the extension names the emitted .js file. The simplest approach is to give aliased imports the same extension:
{
"compilerOptions": {
"module": "nodenext",
"target": "es2022",
"strict": true,
"outDir": "dist",
"paths": {
"@app/*": ["./src/*"]
}
}
}// src/main.ts in a package whose package.json has "type": "module"
import { formatDate } from "@app/utils/date.js";
console.log(formatDate(new Date(0)));The compiler maps @app/utils/date.js to ./src/utils/date.js, then finds date.ts through the usual .js to .ts substitution. This type-checks. It still does not run under plain Node, because Node sees @app/utils/date.js as a bare package name and looks for a package called @app in node_modules.
That failure is the main reason many Node-targeted projects avoid paths. nodenext exists to make the compiler agree with Node, and paths is a place where the two can disagree.
Using package.json imports instead
Node has its own alias feature that the compiler understands: the imports field in package.json. Keys must start with #, which keeps them from colliding with package names. Because Node reads the field itself, the alias works at runtime with no extra tooling.
{
"name": "example-app",
"type": "module",
"imports": {
"#utils/*": "./dist/utils/*.js",
"#config": "./dist/config/index.js"
}
}// src/main.ts
import { formatDate } from "#utils/date.js";
import { config } from "#config";
console.log(formatDate(new Date(0)), config);The targets point at the emitted files in dist. When outDir and the source root are known, TypeScript maps those targets back to the .ts sources for type-checking. That lets one declaration serve both the compiler and Node. Both nodenext and bundler resolution read imports.
Compare the two approaches:
| Question | `paths` | `package.json` `imports` |
|---|---|---|
| Who reads it | The compiler only | Node, the compiler, and most bundlers |
| Alias prefix | Anything, such as `@app/*` or `~/*` | Must begin with `#` |
| Works in plain Node | No | Yes |
| Can differ per runtime | No | Yes, using conditions such as `import` and `require` |
| Can point outside the package | Yes | Yes, but only to files or to other packages by name |
For code that Node runs directly, prefer imports. For code that a bundler processes, paths plus a matching bundler alias is common and acceptable. Many tools can read paths directly, so the duplicate setting can be generated instead of maintained by hand.
Gotchas
Declaration files keep the alias
When you emit declarations with declaration: true, the .d.ts files copy import specifiers as written. A published .d.ts containing import type { User } from "@app/models" breaks for every consumer. Their compiler has no paths entry for @app, so the type usually degrades to an error or to any. Use relative imports inside any code that ends up in a published package. Use # imports only when the field is also published and the targets exist in the package.
paths cannot point at a package's internals reliably
You can map "lodash-local": ["./vendor/lodash/index.ts"], but only the compiler sees it. A package that does the same thing at runtime will resolve to a different copy. The types and the running code then disagree, and the compiler cannot warn you.
Editor and compiler can drift
Editors read the nearest tsconfig.json for a file. In a monorepo, a test folder may have its own tsconfig.json without the paths entries. The same import then resolves in src but fails in test. A project with extends must also remember that paths in the child replaces the parent's paths entirely. It does not merge, and relative locations are resolved against the file where paths is defined.
Type-only fixes hide runtime failures
Adding paths to silence "Cannot find module" is tempting. It can make the error vanish while the program still fails when run. After you add an alias, run the real program or test, not only tsc.
Diagnosing a paths problem
Use the tracing flags from the diagnosing chapter and look for the alias.
npx tsc --noEmit --traceResolution | grep "@app/utils"The trace shows lines like 'paths' option is specified, looking for a pattern to match module name '@app/utils/date' and then each candidate path it tries. If you see Module name ... matched pattern, the compiler found your mapping, so a later failure comes from a wrong target, a missing extension, or a missing file. If no match line appears, the key does not match the specifier. The usual causes are a tsconfig.json that is not the one being used, or a star in the wrong place.
Choosing whether to use paths
- If Node runs your compiled JavaScript with no bundler, use relative imports or
package.jsonimports. - If a bundler builds your code,
pathsis fine, as long as the bundler is configured with the same mapping. - If you publish a library, keep aliases out of the emitted code and declarations.
- If you only want shorter imports and the project is small, consider whether relative imports are simpler. An alias is one more thing that has to be configured in the compiler, the runtime, and the tests.
Exercises
Exercise
A project uses "paths": { "@lib/*": ["./src/lib/*"] } and moduleResolution: "bundler". tsc --noEmit passes. The same code, compiled with tsc and run with node dist/main.js, fails with "Cannot find package '@lib'". Why, and what are two ways to fix it?
Show answer
paths affects only the compiler's resolution. The emitted dist/main.js still contains the @lib/... specifier, and Node treats it as a package name. Fixes: replace the aliases with relative imports (or package.json imports entries such as #lib/* pointing at the files in dist), or run the code through a bundler configured with the same alias. Switching to nodenext would also help the compiler agree with Node about extensions, but it does not by itself make the alias work at runtime.
Exercise
Given "paths": { "@app/*": ["./src/*"], "@app/testing/*": ["./test-utils/*"] }, which location does the compiler use for @app/testing/mock, and why?
Show answer
It uses ./test-utils/mock. Both keys match the specifier, and the compiler chooses the key with the longest prefix before the *. @app/testing/ is longer than @app/.
Exercise
A library you publish contains import type { User } from "@app/models" in src/api.ts, and declaration is on. Consumers report that User is typed as an error or any. What happened and how do you prevent it?
Show answer
The emitted api.d.ts keeps the specifier @app/models unchanged. Consumers have no paths entry for @app, so their compiler cannot resolve it. Prevent it by using relative imports (with the correct extension for your module mode) in source that is published, or by using package.json imports with # specifiers whose targets are shipped in the package.