DEV Community

Alexander Kim
Alexander Kim

Posted on

Setup path aliases w/ React + Vite + TS

Out of the box vite doesn't provide "@" path alias to src, so we have to manually setup it. I suppose you're using Vite preset for react-ts.

Steps to setup this:

Step 1

vite.config.ts:

// also don't forget to `npm i -D @types/node`, so __dirname won't complain
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 would tell Vite about the alias.

Step 2

We're adding "@" alias for src directory (ts needs this).

tsconfig.json:

{
  "compilerOptions": {
    // ...rest of the template
    "types": ["node"],
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}
Enter fullscreen mode Exit fullscreen mode

Usage

import Comp from '@/components/Comp'
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

Collapse
annaspies profile image
Anna

Does this work for nested paths? I'm trying to do something like this, and the nested folder isn't working for me:

{
  "compilerOptions": {
    "baseUrl": ".",
    ...
    "paths": {
      "*": ["src/*", "node_modules/*"],
      "components/*": ["src/components/*"],
      "containers/*": ["src/containers/*"],
      "pages/*": ["src/constants/*"],
      "store/*": ["src/store/*"],
      "types/*": ["src/types/*"],
      "NestedFolder/*": [
        "src/components/NestedFolder/*"
      ],
    }
  },
  "include": ["src/**/*", "*"]
}
Enter fullscreen mode Exit fullscreen mode
Collapse
iamsoprada profile image
IamSoPradaYou

Thank you so much! That really helped me, spent half of my day trying to resolve problems with using aliases.