How to setup path aliases in Vite 2,3 & Typescript

lilarmstrong

Armstrong

Posted on August 10, 2023

How to setup path aliases in Vite 2,3 & Typescript

As of August 2023, this approach still works with Vite version 2 and 3. So whenever I mention Vite, I am referring to the version 2 and 3. Let me know if you encounter any problems in the comment section.

Have you ever thought of how to get rid of imports resembling ../../assets/* or ../../../assets/* in your vite project? Well, this article will help you to do just that.

Reasons for Usage

  • Simplify referencing the project root.
  • Address module resolution errors when modifying files in directories.
  • Satisfy your curiosity

Alias Setup

In this guide, I'll use the alias @ to denote the project root. This approach is demonstrated using a React project scaffolded with Vite. The technique can be applied to Vue, AngularJS, or other frameworks supporting TypeScript. Learn how to scaffold a Vite app here.

Follow these steps to set up path aliases for TypeScript and Vite:


Steps to Follow

  1. Open your project's tsconfig.json file.
  2. Inside the compilerOptions section, add:
   "baseUrl": "src",
   "paths": {
       "@/*": ["./*"]
   }
Enter fullscreen mode Exit fullscreen mode

This informs TypeScript to map module names matching the @/* pattern to src/* at runtime. Note that paths are resolved relative to the baseUrl value of the project.

  1. Update your Vite configuration (vite.config.ts) as follows:
   import { defineConfig } from "vite";
   import { resolve } from "path";

   export default defineConfig({
       // ... other configurations
       resolve: {
           alias: {
               "@": resolve(__dirname, "src")
           }
       }
   });
Enter fullscreen mode Exit fullscreen mode

Ensure you've installed @types/node for improved type checking.

  1. Before:
   import { useState } from "react";
   import reactLogo from "./asset/react.svg";
   import "./App.css";
Enter fullscreen mode Exit fullscreen mode

After:

   import { useState } from "react";
   import reactLogo from "@/asset/react.svg";
   import "@/App.css";
Enter fullscreen mode Exit fullscreen mode

Your application should continue functioning correctly. Feel free to explore other options. If this guide was useful, let me know by commenting, sharing and giving a thumbs up.

💖 💪 🙅 🚩
lilarmstrong
Armstrong

Posted on August 10, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related