Published on

How to Use Import Module Path Aliases like @ in Next.js

Authors

We all know that importing files in our project becomes slightly complex as our app grows with so many nesting. Using a relative path might become a little tedious and hard to maintain later on.

One way to make it simpler is to use a module path alias like @, so you can use a custom alias like @ while importing the file.

For example, you can map @/components to components/* directory.

So that you can import files like this

import HelloWorld from '@/components/HelloWorld.jsx'

Instead of relative path like this:

import HelloWorld from '../../.../HelloWorld.jsx'

Here is how to do it in Next.js

Javascript / Typescript

The configuration is the same for both Javascript and Typescript. But you need to make sure to set it in its respective config file.

In case, if you're on Javascript, the config file will be jsconfig.json and for Typescript, it'll be tsconfig.json in the root of your project (create a new file if it doesn't exist)

Then add the compilerOptions and it'll take care of the rest.

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

Happy Simplified Imports!

Reference