DEV Community

Cover image for Path Aliases in Next.js
Abdulrahman Afaraetu
Abdulrahman Afaraetu

Posted on • Updated on

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

Discussion (3)

Collapse
larsonnn profile image
Lars Feldeisen • Edited on

Well this would not work and components will not be resolved.
Components are in your src folder. But the compilation is done in the root folder. You need to change it.

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@/components/*": ["/src/components/*"]
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Or by changing the baseUrl

{
    "compilerOptions": {
        "baseUrl": "./src/",
        "paths": {
            "@/components/*": ["/components/*"]
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
gbotemi_dev profile image
gbotemi_dev

His approach worked fine for me. Your second approach of changing the baseUrl also worked fine. But your first approach didn't work.

Collapse
tylerjusfly profile image
Momoh Taiwo Tyler

Enlightening boss. Good Job
I'm proud of you.