⚠️ This lesson is retired and might contain outdated information.

Adding absolute imports to Next.js app

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet

This is a small DX improvement: instead of writing ../../../../../components over and over again in our code, we'd like to have a consistent way of importing components directory using @components no matter which directory we're currently at.

In this quick lesson we're going to learn how to add absolute imports to a Next.js app.

Tomasz Łakomy: [0:00] Before we continue, we're going to implement a small developer experience improvement. Because here, we can see that in order to get the article component from the components directory, we have to know the relative path between the file that we are currently editing and the components directory.

[0:17] This can get rather confusing in larger projects. Luckily, Next has introduced absolute imports, which will help us solve this problem.

[0:25] To add absolute imports, go to tsconfig.json and I'm going to add two things. First off, the baseUrl, which I'm going to set to the current path. Next, we have to specify the paths. Whenever, no matter how deep in the componentry, we're going to import @components/*, in fact, we're going to get from the baseUrl, that is the current root directory, we're going to get the folder components and any file.

[0:51] If I go back to our [title] .tsx file, as in our blog post, instead of using those two slashes, I can just replace it with an @ sign. Here we can see that this is in fact going to get the Article component from the components directory.

[1:07] We can go ahead, and we'll suffix that in the About page, as well in this hello page. Now, no matter how many nested pages we have, we can always easy to get a component from the components directory by using this absolute import.