Vite

Resolving TypeScript path aliases in Vite projects

Keep TypeScript and Vite path aliases aligned with resolve.alias or vite-tsconfig-paths, then verify module resolution and type safety in CI.

Resolving TypeScript path aliases in Vite projects

Moving a deeply nested component often means rewriting a string of ../ imports. Path aliases make those imports easier to read, as long as TypeScript and Vite agree on the files they point to.

The examples use Vite, TypeScript, and pnpm. The plugin example uses vite-tsconfig-paths.

Why an alias can work in the editor and fail in Vite

With a feature-oriented folder tree, even a small refactor can change the number of parent directory segments required to reach a shared component. A path such as @components/UserCard names the dependency without encoding the caller’s folder depth.

1
2
3
4
// Relative imports change when the caller moves
import { UserCard } from '../../../../components/UserCard';
import { fetchUserProfile } from '../../../../services/userService';
import { formatDate } from '../../../../utils/formatDate';

TypeScript’s compilerOptions.paths describes how the type checker resolves module names. It does not rewrite those imports for whatever tool runs the application. Vite also needs to resolve each import to a real module. An IDE can offer correct completions while the development server throws [plugin:vite:import-analysis] Failed to resolve import "@/components/Button". The opposite happens if only Vite knows the mapping and TypeScript reports TS2307.

flowchart TD
    subgraph TwoToolsProblem["TypeScript and Vite use separate resolution settings"]
        TS["tsconfig.json (compilerOptions.paths)"] -->|"Resolve paths"| IDE["VS Code types and completions work"]
        Vite["vite.config.ts (resolve.alias missing)"] -->|"Module not found"| DevServer["Vite serve and build fail"]
    end
SetupAdvantageMaintenance
TypeScript paths plus explicit Vite aliasesFew moving parts for a small projectUpdate two sets of entries together
TypeScript paths through vite-tsconfig-pathsTypeScript and Vite share source import patternsEnsure the plugin sees the right project configs and file types

Define matching aliases by hand

Vite accepts aliases under resolve.alias. For filesystem substitutions, use absolute targets. In a Node.js ESM config, fileURLToPath(import.meta.url) provides a reliable path that can be passed to path.resolve.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// vite.config.ts
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)),
      '@components': fileURLToPath(new URL('./src/components', import.meta.url)),
      '@services': fileURLToPath(new URL('./src/services', import.meta.url)),
      '@utils': fileURLToPath(new URL('./src/utils', import.meta.url))
    }
  }
});

The TypeScript project should describe the same prefixes. The wildcard in paths applies to the portion of the module name after the prefix.

1
2
3
4
5
6
7
8
9
10
11
12
// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@components/*": ["src/components/*"],
      "@services/*": ["src/services/*"],
      "@utils/*": ["src/utils/*"]
    }
  }
}

I keep manual mappings when there are only a couple of aliases or when a bundler substitution deliberately has no TypeScript equivalent. Once the structure changes frequently, two config files make drift easy.

Read TypeScript paths through the Vite plugin

Install the plugin as a development dependency.

1
2
# bash
pnpm add -D vite-tsconfig-paths

Register it in the Vite plugin array. The plugin participates in module resolution and uses the importing file’s TypeScript configuration to map supported aliases.

1
2
3
4
5
6
7
8
9
10
11
12
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
  plugins: [
    react(),
    // Resolve imports using paths from tsconfig.json
    tsconfigPaths()
  ]
});

The root config defines the following paths.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["DOM", "DOM.Iterable", "ES2022"],
    "module": "ESNext",
    "moduleResolution": "bundler",
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@components/*": ["src/components/*"],
      "@services/*": ["src/services/*"],
      "@utils/*": ["src/utils/*"]
    },
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src"]
}

The editor uses these paths for type resolution, and the Vite plugin uses them when resolving imports it handles. CSS imports have different resolution requirements, so check the plugin documentation or use an explicit Vite alias for those imports.

Vite production build showing successful TypeScript alias resolution Figure 1. The sample production build completes in 368 milliseconds with four TypeScript path patterns.

Run the type checker as a separate build step

Vite transpiles TypeScript without running TypeScript’s full type checker. A successful bundle proves Vite could resolve and transform imports in that bundle. It does not prove the compiler found no type errors. I run tsc --noEmit before vite build in CI.

1
2
3
4
5
6
7
8
// package.json
{
  "scripts": {
    "dev": "vite",
    "typecheck": "tsc --noEmit",
    "build": "tsc --noEmit && vite build"
  }
}

Terminal output confirming a clean tsc noEmit run Figure 2. The sample project’s TypeScript check finds no alias errors.

When diagnosing a mismatch, --traceResolution shows how the TypeScript resolver interpreted each import. --explainFiles can show why the resolved files are in the program. Compare that information with the Vite error or plugin log. A typo in the alias prefix and an importer outside a config’s include pattern can look identical in the browser.

Check project ownership in a monorepo

A pnpm workspace, Nx monorepo, or Turborepo can have several tsconfig.json files. Confirm which package owns each importer and which configuration it inherits. The plugin can discover configurations automatically, and the projects option provides an explicit selection where discovery chooses an unintended project.

1
2
3
4
5
6
7
8
9
10
11
// vite.config.ts (monorepo)
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
  plugins: [
    tsconfigPaths({
      projects: ['./tsconfig.json', '../../packages/*/tsconfig.json']
    })
  ]
});

I verify one alias import from each package that builds an application. Then I check that shared libraries don’t rely on aliases defined only in one app. An alias is useful when it makes package boundaries clearer. If it hides an accidental cross-package dependency, I prefer an explicit package import.

This post is licensed under CC BY 4.0 by the author.