What import alias would you like configured in Next.js

April 10, 2023 | 1 Minute Read

Since Next.js 13, when you create a new Next.js app, you will be asked a question like:

So what exactly is it asking? Let me help you.

When you are importing components in your pages, you must have done something like this:

import NewPost from "../../components/Post/New";

While this works, it’s a tiring thing to do at every place because the path differs relative to where your desired file is from your current file( hence called relative path).

To make it easier, you can add the option in your jsconfig.json or tsconfig.json( depending on if you use TypeScript or JavaScript for your Next.js app) like so:

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@/components/*": ["components/*"],
        }
    },
    "exclude": ["node_modules", ".next"]
}

In the paths key, we have added a path alias for components. What does this mean? It means now you can access everything inside your components folder as:

import NewPost from "@/components/Post/New";

This looks cleaner and you don’t have to worry about how many dots you need which is a timesaver.

Next.js has now decided to include this option when creating the app so you don’t have to add it later on.

So when asked what import alias you like configured you can always enter:

components/*

If you want more tutorials like this or have questions about this tutorial, follow me on Twitter. Also if you want to receive it in your email, subscribe to the newsletter! Thanks for your time!