Change relative path to alias import in vite react-typescript

·

2 min read

Change relative path to alias import in vite react-typescript

Table of contents

In modern react applications relative imports look like weired.

So I will guide the step-by-step approach to setting up alias path import in this article.

Step 1: In the tsconfig.json file change baseurl to './' or "./src".

Step 2:Then In the second step set paths to where you want to configure paths to map as given below in the image and change accordingly.

Step 3:Then install the path from the command `npm i path` for setting the path in the second file vite.config.ts

Step 4:Then import the path in the vite.config.ts file for setting the path in this file.

and if __dirname not found shows an error not found install `npm i -D @types/node` for resolving that error and restart Code Editor.

Step 5: In the vite.config.ts file also change accordingly to match the same name you define in the tsconfig.json for paths.

Step 6: Easily import the components and file you want to import it will start giving suggestions.

Conclusion

Transitioning from relative path imports to alias imports in a Vite React-TypeScript project is a smart move that can significantly improve code maintainability and readability. By setting up aliases for your commonly used directories and modules, you streamline the import process, making your codebase more organized and less error-prone. This change allows you to focus on the logic and functionality of your application rather than getting bogged down in complex directory traversal. With the power of Vite's fast development server and TypeScript's type-checking, your project will benefit from both improved developer productivity and enhanced code quality.