Absolute Import Next JS Typescript
Haikel, 1 min read / February 1, 2023
بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ
Every time we create a new Next JS Project, by default it uses relative import.
import { getSlugs } from "../../lib/helpers/getSlugs";
At first, it looks simple. But as our project can be more complex and bigger, it can be difficult to maintain and use. Absolute import can simplified that.
Before using absolute import, we must configure our tsconfig.json
file. In tsconfig.json
, more spesific in compilerOptions
, we can add the configuration like this:
{
"compilerOptions": {
"baseUrl": "./src"
}
}
I use src folder. So, the folder like pages
, styles
which was originally in root directory, i can move it to src
folder.
We also can configure path aliases, like this:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"~/*": ["*"]
}
}
}
Because i've already set baseUrl
to src
, then i dont need to import components like this src/components/*
.
For the paths
, you can adjust it with your project structure.
So, for importing file, we can do that like this:
import { getSlugs } from "~/lib/helpers/getSlugs";