DEV Community

Cover image for Configuring/ fixing absolute path in a react, typescript and vite project.
Anoop
Anoop

Posted on

Configuring/ fixing absolute path in a react, typescript and vite project.

If you are someone trying to configure absolute import in a react, ts and vite project or facing issue with resolving absolute paths in same, this post is for you.

Recently I tried to make my hands dirty by building something in react and decided to use typescript and vite in the project.

I didn’t want to use the relative import (import Sidebar from “../components/Sidebar”;) as it leads to longer and less readable import paths as well as it will be difficult to manage when the project grows.

So I decided to use the absolute import (import { Sidebar } from ‘@components/Sidebar’;)

In order to configure absolute import in this project there are few things we have to add in tsconfig.json and vite.config.ts file.

In the tsconfig.json file add the baseUrl and paths, example code is given below

{
"compilerOptions": {
...
"baseUrl": "./src",
"paths": {
"@components/*": ["components/*"],
"@constants/*": ["constants/*"],
"@pages/*": ["pages/*"]
}
},
...
}

The above code tells typescript how to resolve import paths.

But that is not enough, we have to tell vite on how to build import path. For this you can use this plugin https://www.npmjs.com/package/vite-tsconfig-paths.

After installing vite-tsconfig-paths plugin, import tsconfigPaths from it and add it to the plugins array in vite.config.ts file as below

`
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
plugins: [react(), tsconfigPaths()],
});
`

With this configurations we will be able to setup absolute import in a react, ts and vite project.

Top comments (0)