- Published on
How to Use TypeScript Path Aliases in Vite
- Authors
- Name
- Ripal & Zalak
How to Use TypeScript Path Aliases in Vite
Configuring and using TypeScript path aliases in Vite can simplify imports in your project by replacing long, relative paths with clean and intuitive aliases. In this guide, we’ll show you how to set up path aliases in your Vite project with step-by-step examples and best practices.
Problem
When working with TypeScript, path aliases allow you to write cleaner import paths like @/shared/types
instead of ../../shared/types
. However, Vite doesn’t automatically recognize the paths
defined in your tsconfig.json
, leading to errors like:
Failed to resolve import "@/shared/types"
To fix this, you need to configure both your tsconfig.json
and vite.config.ts
files. Let’s see how.
Solution
tsconfig.json
Step 1: Configure First, define your path aliases in tsconfig.json
. Here’s an example:
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": ["src/*"],
"@shared/*": ["src/shared/*"]
}
}
}
In this example:
@/*
maps to thesrc
directory.@shared/*
maps to thesrc/shared
directory.
vite.config.ts
Step 2: Update To make Vite recognize these aliases, you need to configure them in vite.config.ts
. There are two main approaches:
path.resolve
Approach 1: Using import { defineConfig } from 'vite'
import path from 'path'
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
'@shared': path.resolve(__dirname, 'src/shared'),
},
},
})
vite-tsconfig-paths
Plugin
Approach 2: Using the For a more automated solution, use the vite-tsconfig-paths
plugin. Install it using:
npm install --save-dev vite-tsconfig-paths
Then update your vite.config.ts
file:
import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'
export default defineConfig({
plugins: [tsconfigPaths()],
})
This plugin automatically reads your tsconfig.json
file and configures path aliases in Vite.
Verifying the Setup
- Add the following import statement in your project:
import { someFunction } from '@/shared/utils'
- Run the Vite development server:
npm run dev
If everything is set up correctly, your project should compile without any errors.
FAQs
1. Why does Vite require separate alias configuration?
Vite doesn’t automatically recognize TypeScript’s paths
because it uses Rollup under the hood. You need to explicitly map these aliases in vite.config.ts
to make them work.
2. Can I use path aliases in JavaScript files?
Yes, path aliases work in JavaScript files as well. You just need to configure them in vite.config.ts
.
tsconfig.json
files?
3. What if I use a monorepo or multiple You can use the vite-tsconfig-paths
plugin to handle complex setups. It automatically resolves paths from the appropriate tsconfig.json
files in your project.