Headless Logo

HEADLESS TEAM

Ivo's Daily Blog

Embrace the Dev World: A Cherished Blog for Developers Everywhere

Innovative Tech Upgrades | Cutting-edge Tech Updates | Weekly Troubleshooting Tales & Beyond!

Ivaylo Tsochev

Why everyone should use absolute imports in React or Nextjs

February 28, 2023

Ivaylo Tsochev

Ivaylo Tsochev

If you’re working on a React or Nextjs project, you should be using absolute imports. In this article, I’ll discuss the why and the how of absolute imports in React and Nextjs projects.

React

Development

If you’re working on a React or Nextjs project, you should be using absolute imports. In this article, I’ll discuss the why and the how of absolute imports in React and Nextjs projects.

There are a few benefits to using absolute imports:

So instead of writing this:

Blog Post Image

Use this:

Blog Post Image

There are a few ways to set up absolute imports in React and Nextjs projects.

If you’re not using “create-react-app”, you can still set up absolute imports in your project. You’ll just need to do the following steps:

Blog Post Image

For example, if you have a file called “Button.js” in the “src/components” directory, your import would look like this:

Blog Post Image

If you’re using TypeScript, you can also set up absolute imports by adding the “paths” option to your “tsconfig.json” file. For example:

Blog Post Image

or maybe something like this:

Blog Post Image

With this option, you can import any file in your project by using the “@” prefix.

For example, if you have a file called “Button.tsx” in the “src/components” directory, your import would look like this:

Blog Post Image

There are a few other ways to set up absolute imports, but these are the two most popular methods.

Do you have any questions about absolute imports in React or Nextjs? Let me know in the comments! And be sure to check out my other React tutorials, like this one on setting up useMemo hook. Thanks for reading!