How to set up path Alias in react.

I'm not sure if this is the right title for this, but it took me a while to find a solution for this, So I'm keeping this here.

Note: I'm assuming you are using react with vite.

Add this to the tsconfig.json file under the compilerOptions object.

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

Install @types/node to dev dependency for type safety for importing from the path module.

yarn add -d @types/node

And change the vite.config.ts to understand the @ sign as well as an alias of the "src" folder.

import path from 'path'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
})

This solution was extracted from Borris's article.

End.

ย