Why everyone should use absolute imports in React or Nextjs
February 28, 2023
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:
- It makes your code more readable — relative imports can be confusing, especially when you’re nesting them. Absolute imports make it clear where each component is coming from.
- It makes your code more portable — if you ever need to move a file, you won’t have to go through and update all of your imports.
- It can make your build process faster — if you’re using a tool like Webpack, absolute imports can help it optimize your code better.
So instead of writing this:
Use this:
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:
- First, create a file called “jsconfig.json” at the root of your project.
- Next, add the following code to “jsconfig.json”:
- Finally, make sure that all of your imports are relative to the “src” directory.
For example, if you have a file called “Button.js” in the “src/components” directory, your import would look like this:
If you’re using TypeScript, you can also set up absolute imports by adding the “paths” option to your “tsconfig.json” file. For example:
or maybe something like this:
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:
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!