Skip to content
jshacks.dev
Tooling

Configure TypeScript paths in Vite and Vitest

Make TypeScript path aliases work in Vite and Vitest by repeating the alias in resolve.alias, or reading it from tsconfig with a plugin.

1 min read
Summarize in AI

TypeScript's paths option only helps the type checker. It does not rewrite imports, so Vite and Vitest need the alias too.

tsconfig.jsonJSON
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": { "@/*": ["src/*"] }
  }
}
vite.config.jsJavaScript
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vite';

export default defineConfig({
  resolve: {
    alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) },
  },
  test: { environment: 'node' },
});
src/main.tsTypeScript
import { formatPrice } from '@/lib/format';

Vitest reads vite.config.js, so one resolve.alias entry serves the dev server, the build and the tests. Without it, the editor is happy and the run fails with Failed to resolve import "@/lib/format". Keeping two lists in step is the weak point; the vite-tsconfig-paths plugin reads tsconfig.json so the list lives in one file. See [the paths option](https://www.typescriptlang.org/tsconfig/#paths).

Use the test key only when you import defineConfig from vitest/config, which types it. The plain vite import still runs it but flags a type error.

Also inTypeScript
Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
Tooling

Create a Vite project from a template

Create a Vite project from a template with npm create vite, choose the vanilla-ts or react-ts template and see which files it generates.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.