Skip to content

Use Absolute Import in React, TypeScript in 2 Steps

How do you write your module imports?

If you write relative paths like this ../../../../SomeComponent, it’s hard to understand when it comes deep structure. On the other hand, we can import with absolute paths like @/src/components/Layout/SomeComponent, which start from a higher level in the directory.

So my goal is import files using absolute paths in React / TypeScript.

Requirements

  • React
  • TypeScript
  • Vite

Folder structure example

/
  src/
    components/
      SomeComponent.tsx
    index.tsx
  tsconfig.json
  vite.config.ts

Configuration Steps

1. Add the following to tsconfig.json

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

2. Add the following to vite.config.ts

export default defineConfig({
  plugins: [
    ...
  ],
  resolve: {
    alias: {
      "@/src": "/src"
    },
  },
});

That’s all. It’s very simple. And now we have a clean import.

Here’s a small sample.

src
|-- components/
|   |-- Button/
|       |-- Button.tsx
|
|-- pages/
    |-- UserProfile/
        |-- UserProfile.tsx

If you want to import Button.tsx, you can wrtie like this:

import Button from "@/src/components/Button/Button";