Sub topic 5
Setting up path aliases
This chapter assumes you can read TypeScript module syntax, you have a React project built with Vite or webpack, and you know the feature-based layout from the earlier chapters. By the end you will be able to configure an @/ alias that works in the compiler, the bundler, the test runner, and ESLint, and you will know where it breaks.
Why aliases help
In a feature-based layout, files sit several folders deep. Without an alias, a component reaching into another feature writes something like this:
import { useCart } from "../../../cart/hooks/useCart";Relative paths like this have three problems:
- The depth changes whenever you move the file, so imports break during refactors.
- The path says nothing about where the code lives. You must count
..segments to find it. - Reviewers cannot tell at a glance whether an import crosses a feature boundary.
A path alias maps a short prefix to a folder. With @/ pointing at src/, the same import becomes:
import { useCart } from "@/features/cart";The import now reads the same from any file in the project. It also names the feature, which makes boundary violations visible.
An alias is configured in several places
An alias is not a language feature. Each tool that reads your imports resolves them on its own, so each tool needs the same mapping.
| Tool | What it does with imports | Needs alias config |
|---|---|---|
| TypeScript compiler and editor | Type checks and offers autocomplete | `paths` in `tsconfig.json` |
| Bundler (Vite, webpack) | Finds the files to build the app | `resolve.alias` |
| Test runner (Vitest, Jest) | Loads modules while tests run | Its own alias or mapper setting |
| ESLint | Applies import rules | Usually reads patterns as text, but import-resolver plugins need config |
The most common mistake is to configure only tsconfig.json. The editor then shows no errors, but the build fails with "Cannot resolve" because the bundler never heard of @/.
Step 1: Configure TypeScript
Add a paths entry to tsconfig.json. The paths option resolves relative to baseUrl. In current TypeScript versions (4.1 and later) you can omit baseUrl and write paths relative to the tsconfig.json file itself.
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}The * on both sides is a wildcard. @/features/cart becomes ./src/features/cart.
TypeScript only uses paths for type checking. It does not rewrite the import in the emitted JavaScript. That is why the bundler needs its own setting.
Step 2: Configure the bundler
Vite
Vite takes the alias in vite.config.ts. Use a URL-based path so it works in ES module projects:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { fileURLToPath, URL } from "node:url";
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
},
},
});Here the key is @, not @/*. Vite matches the prefix, so @/features/cart resolves correctly.
webpack
In webpack the setting is resolve.alias, and you build an absolute path with path.resolve:
// webpack.config.js
const path = require("path");
module.exports = {
resolve: {
extensions: [".ts", ".tsx", ".js"],
alias: {
"@": path.resolve(__dirname, "src"),
},
},
};If you do not want to maintain two copies of the mapping, the tsconfig-paths-webpack-plugin reads the paths from tsconfig.json. For Vite, the vite-tsconfig-paths plugin does the same. These plugins remove the risk of the two configs drifting apart, at the cost of one more dependency.
Step 3: Configure the test runner
Tests load modules through their own resolver, so aliases fail there too unless you configure them.
With Vitest, which reads vite.config.ts, the Vite alias already applies. If you keep a separate vitest.config.ts, repeat the resolve.alias block there.
With Jest, use moduleNameMapper:
// jest.config.js
module.exports = {
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
},
};The regular expression captures everything after @/ and maps it into src. Note the different syntax: Jest uses a regular expression, TypeScript uses a glob-like wildcard.
Choosing a prefix
@/ is the most common prefix, and it works well when your own code lives in one src folder. Two cautions apply:
- Scoped npm packages also start with
@, such as@tanstack/react-query. A bare@alias would collide with them. The trailing slash in@/avoids this, because no scoped package name begins with@/. - Avoid prefixes that look like real packages, such as
src/orapp/, without a symbol. They resolve to your folder only by accident and confuse newcomers.
Some teams add more than one alias, for example @/features/* and @/shared/*. This is rarely worth it. One alias into src keeps the configuration small, and the folder names already carry the meaning.
Using aliases with boundaries
An alias makes a cross-feature import easy to write, so it also makes a bad import easy to write. Consider these two lines:
import { useCart } from "@/features/cart";
import { calcTotals } from "@/features/cart/utils/calcTotals";The first uses the feature's public API. The second reaches into its internals. Both compile. The alias does not enforce anything; it only shortens the path.
The shape @/features/<name>/<something> is easy to detect by pattern, which is why the ESLint rule in the boundary chapter matches @/features/*/*. Set up the alias first so that rule has a consistent import form to match.
Inside a feature, prefer relative imports for files in the same feature:
// src/features/cart/components/CartList.tsx
import { useCart } from "../hooks/useCart";This keeps a feature portable. If you rename or move the feature folder, its internal imports keep working. Use the alias for imports that cross a feature boundary or reach into shared.
Common errors
- Editor works, build fails. The
tsconfig.jsonhaspaths, but the bundler has no alias. Add the bundler setting. - Build works, tests fail. The test runner has its own resolver. Add
moduleNameMapperor the Vitest alias. - Autocomplete does not offer
@/imports. The editor uses a differenttsconfig.jsonthan you edited. In projects with several config files (for exampletsconfig.app.json, which Vite templates generate), putpathsin the one that includessrc. - Wrong mapping after moving
src. Paths inpathsare relative to the config file. Moving the config changes what./src/*means. - Circular imports appear. Aliases do not cause cycles, but they hide them because the paths look clean. Index files that re-export everything are a frequent source.
Verifying the setup
Create one file that uses the alias and run each tool against it:
- Run
npx tsc --noEmitand confirm there are no unresolved-module errors. - Run the dev server and the production build.
- Run one test that imports through
@/.
If all three pass, the configuration agrees across tools.
Exercise
Your editor shows no errors for import { Button } from "@/shared/ui/Button", but npm run build fails with "Cannot resolve". Test runs also fail. What is missing, and which two places need the fix?
Show answer
Only tsconfig.json has the paths entry. TypeScript uses it for type checking and does not rewrite imports in the output. Add the alias to the bundler (resolve.alias in Vite or webpack) and to the test runner (moduleNameMapper in Jest, or the Vite alias that Vitest reads).
Exercise
A file at src/features/cart/components/CartList.tsx needs useCart from the same feature and formatDate from src/shared/lib. Which import should use the alias, and why?
Show answer
formatDate should use the alias (@/shared/lib/formatDate) because it crosses out of the feature. useCart should use a relative path (../hooks/useCart) because it stays inside the feature, which keeps the feature movable.