DEV Community

Tyler
Tyler

Posted on

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/*"]
}
Enter fullscreen mode Exit fullscreen mode

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

yarn add -d @types/node
Enter fullscreen mode Exit fullscreen mode

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'),
    },
  },
})
Enter fullscreen mode Exit fullscreen mode

Solution was extracted from Borris article.

End.

Top comments (0)