Path Aliases in Next.js

Path Aliases in Next.js

I recently started learning Next.js and used path aliases in a project, and guess what? It significantly improves the quality of my code. Are you curious as to how this is possible? Let me show you how it's done...

What is the problem? "Relative Path Hell"

Typing paths is time-consuming and error-prone and it can be complicated at times. Even with code completion capabilities like IntelliSense (which is supported by practically every IDE or text editor), as your codebase expands, this might become increasingly difficult.

Here's an example of a relative path that requires accessing many path levels when attempting to import.

Relative path

How can we solve this?

Shortening our import paths, which can be accomplished via "Path Aliases," can make things a little easier.

path aliases


How can we build up path aliases in a project that is structured like this?

Project Structure

  • To make use of path alias, create a "jsconfig.json" file or ("tsconfig.json" if using typescript) in the project root and configure it as shown below.

alias config

What next?

There's nothing further to set up; you can now use path aliases in your application while importing.

In conclusion, every update to the "json" file necessitates a server restart.

I would like to connect with you. LinkedIn Github Twitter