back

Clean imports in Next.js

Relative imports get ugly fast. Once you're three folders deep, everything turns into ../../../components/Button and you lose track of where anything actually lives.

Next.js supports absolute imports out of the box since 9.4. Add baseUrl to your tsconfig.json or jsconfig.json:

{
  "compilerOptions": {
    "baseUrl": "."
  }
}

Now you can import from the project root directly:

import Button from "components/Button";

If you want a prefix to distinguish your code from node_modules, add paths:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}
import Button from "@/components/Button";

No babel plugin, no webpack config. Your editor picks this up too. Command+Click in VSCode jumps to the right file, and auto-imports resolve correctly.

One less thing to think about.