Paper cover
Paper icon

How to avoid deeply nested imports in Next.js

Learn how to harvest the power of absolute imports and module aliases in Next.js

Code
Organization
Next.js
Sep 16, 2022 2 min read

Intro

When a project starts to grow in size and complexity, you might start to notice some undesirable patterns. A common example of this is when you need to access a distant file within the hierarchy, leading to chaotic import statement such as import Footer from "../../../components/Footer"

If you’re using Next.js, then starting from version 9.4 you can harvest the power of absolute imports and module aliases to simplify your import statements. This means that no matter where you are in the folder structure, you can directly import files like this:

1import Logo from "public/logo.svg"; // Absolute import
2import Navbar from "@/components/Navbar"; // Module alias

Absolute imports

To get started, all you have to do is configure the baseUrl inside your jsconfig.json (JS projects) or tsconfig.json (TS projects). If you don’t have one already, just create it at the root of your project.

1{
2  "compilerOptions": {
3    "baseUrl": "."
4  }
5}
jsconfig.json or tsconfig.json

The baseUrl is the location to start the import from, and the . specifies it as the root directory. Now, you can use absolute imports to make import statements such as this:

1import Footer from "src/components/Footer";

Module aliases

If you’d like to go a step further, you could also configure the paths option to create custom module aliases. This is especially useful for accessing frequently used folders that are deeply nested within your project structure.

Here is an example of how we can configure the paths option.

1{
2  "compilerOptions": {
3    "baseUrl": ".",
4    "paths": {
5      "@/components/*": ["src/components/*"],
6      "@/hooks/*": ["src/hooks/*"],
7      "@/lib/*": ["src/lib/*"]
8    }
9  }
10}
jsconfig.json or tsconfig.json

The object key represents the alias that you’d like to give, and the value is an array of paths that it should map to. Now, you can use module aliases to make import statements such as this:

1import Footer from "@/components/Footer";

Just note that in order to define the paths option, the baseUrl must also be specified. Also, make sure to restart your development server with next dev to apply the changes.

Conclusion

Using absolute imports and module aliases can help you make import statements that are a lot more direct and concise. It integrates well with most modern editors (such as VSCode) and you don’t have to touch your imports when moving a file to a different location.

You can also combine this with barrel exports and take your import statements a step further.


All static files and source code used in this page can be found on GitHub and edited on Codesandbox.