DEV Community

Muhammad_Dwi_Prasetyo
Muhammad_Dwi_Prasetyo

Posted on

Setup path aliases in React + Vite + TS Project

Out of the box, vite doesn't provide an "@" path alias for src, but you can define your own aliases. I assume you are using the Vite preset for react-ts.

The steps to set this up:

Step 1:

install devDependencies @types/node // so that __dirname can be recognized

npm i -D @types/node
Enter fullscreen mode Exit fullscreen mode

in vite.config.ts:

// ...
import * as path from 'path'

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: [{ find: '@', replacement: path.resolve(__dirname, 'src') }],
  },
})
Enter fullscreen mode Exit fullscreen mode

This will inform Vite of his alias.

if you want to have many aliases you can make it like this:

// ...
import * as path from 'path'

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: [
      { find: '@', replacement: path.resolve(__dirname, './src') },
      { find: '@components', replacement: path.resolve(__dirname, './src/components/') },
      { find: '@assets', replacement: path.resolve(__dirname, './src/assets') },
      { find: '@data', replacement: path.resolve(__dirname, './src/data') },
      { find: '@pages', replacement: path.resolve(__dirname, './src/pages') },
      { find: '@public', replacement: path.resolve(__dirname, './public/') },
    ],
  },
})
Enter fullscreen mode Exit fullscreen mode

or

// ...
import * as path from 'path'

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
      '@components': path.resolve(__dirname, './src/components/'),
      '@assets': path.resolve(__dirname, './src/assets'),
      '@data': path.resolve(__dirname, './src/data'),
      '@pages': path.resolve(__dirname, './src/pages'),
      '@public': path.resolve(__dirname, './public/'),
    },
  },  
})
Enter fullscreen mode Exit fullscreen mode

for alias naming can be done freely, I added @ in front of the alias name just to indicate it is an alias, this is just my optional approach. this is all up to you.

Step 2:

We add the alias "@" to the src directory in tsconfig.json

tsconfig.json:

{
  "compilerOptions": {
    // ...

    "types": ["node"],
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*", "./dist/*", ""],
      "@components/*": ["src/components/*"],
      "@assets/*": ["src/assets/*"],
      "@data/*": ["src/data/*"],
      "@pages/*": ["src/pages/*"],
      "@public/*": ["public/*"]
    }
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}
Enter fullscreen mode Exit fullscreen mode

Usage:

on the file you want to import an alias:

import Comp from '@components/Comp..'

// ...
Enter fullscreen mode Exit fullscreen mode

that's all, hope it's useful 潃

Top comments (0)