Published on

How to Use TypeScript Path Aliases in Vite

Authors
  • Name
    Ripal & Zalak
    Twitter

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

Step 1: Configure tsconfig.json

First, define your path aliases in tsconfig.json. Here’s an example:

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"],
      "@shared/*": ["src/shared/*"]
    }
  }
}

In this example:

  • @/* maps to the src directory.
  • @shared/* maps to the src/shared directory.

Step 2: Update vite.config.ts

To make Vite recognize these aliases, you need to configure them in vite.config.ts. There are two main approaches:

Approach 1: Using path.resolve

import { defineConfig } from 'vite'
import path from 'path'

export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@shared': path.resolve(__dirname, 'src/shared'),
    },
  },
})

Approach 2: Using the vite-tsconfig-paths Plugin

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

  1. Add the following import statement in your project:
import { someFunction } from '@/shared/utils'
  1. 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.

3. What if I use a monorepo or multiple tsconfig.json files?

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.