⚠️ 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
Published 4 years ago
Updated 2 years ago

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.

egghead
egghead
~ 12 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today