Easy way to use absolute path in Vite and React with Typescript

Thawinwats
1 min readSep 22, 2022

--

How to use absolute path using Vite and React with Typescript

How to use absolute Imports using Vite and React with Typescript
Easy way to use absolute Imports in Vite and React with Typescript

If you are lazy to import like this below

import Button from '../../../button'

let's replace it with using the Absolute Path or Absolute Imports

import Button from 'components/button'

let me introduce your vite-tsconfig-paths.
Give vite the ability to resolve imports using TypeScript's path mapping.

First Install as a dev dependency

// With NPM
$ npm i -D vite-tsconfig-paths
// With Yarn
$ yarn add -D vite-tsconfig-paths
// With PNPM
$ pnpm add -D vite-tsconfig-paths

And inject vite-tsconfig-paths using the vite.config.ts module

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tsconfigPaths from 'vite-tsconfig-paths'
export default defineConfig({
plugins: [react(), tsconfigPaths()],
})

Now open your tsconfig.json

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

The last step is to restart Vite when you update your paths mappings.

--

--

Thawinwats
Thawinwats

No responses yet