DEV Community

Cover image for Stop Writing ../../../../../../ in Your Imports
Aabhas Sao
Aabhas Sao

Posted on

Stop Writing ../../../../../../ in Your Imports

Something clicked for me recently when I was staring at this line in my codebase:

import Button from "../../../../../../components/Button.tsx"
Enter fullscreen mode Exit fullscreen mode

Six levels deep. And honestly, what does that even tell you? You have to mentally trace backwards from wherever you currently are just to figure out where that file lives. The path is relative to this file, which means it looks different in every single file that imports the same component.

There is a cleaner way.

import Button from "@/components/Button.tsx"
Enter fullscreen mode Exit fullscreen mode

Same component. But now the path is absolute, it reads clearly, and it looks identical no matter which file you paste it into. You immediately know where to find it in the project. No counting ../ hops.

Setting It Up

It takes about five minutes. In your tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

If you are using Vite:

// vite.config.ts
import { defineConfig } from "vite"
import path from "path"

export default defineConfig({
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"),
    },
  },
})
Enter fullscreen mode Exit fullscreen mode

Webpack has its own resolve.alias config, same idea.

The VSCode Thing

By default, VSCode still suggests relative imports even after you set up aliases. To fix that, add this to your settings:

"typescript.preferences.importModuleSpecifier": "non-relative"
Enter fullscreen mode Exit fullscreen mode

After that, auto import suggestions will use @/ paths instead of ../ chains.

When Are Relative Imports Actually Fine?

Honestly, for files that are right next to each other. If you have utils.ts sitting right beside index.ts, doing import { helper } from "./utils" is totally fine. The problem starts when you cross multiple folders.

The rule I follow: if the import needs more than one ../, reach for the alias.

The One Upside of Relative Imports

Zero setup. They work out of the box in every project. That is their only real advantage, and it stops mattering the moment a project grows past a handful of files.


Most serious projects configure path aliases from day one now. If your current project does not have it set up, it is worth the five minutes. Future you, three months from now, deep in a nested feature folder, will appreciate it.

JavaScript Dev

No JavaScript, it's a no. Quite funny how when I used JavaScript extensively. I used to hate Java's quirks, and today I'm picking on JavaScript.

Now off you go, clean up the imports.

Top comments (0)