Absolute paths imports in NextJs

Do you find yourself writing Nextjs components imports paths like the one below?

import SiteNav from '../../components/common'
export default ()=> {
    <SiteNav />
}

If the answer is yes, then you can benefit from the absolute paths imports feature. In order to activate the absolute imports, you will need to edit the contents of jsconfig.json (or tsconfig.json if you are using typescript). You will need to set up the compilerOptions.baseUrl property.

{
  "compilerOptions": {
    "baseUrl": "."
  }
}

If you don't have the jsconfig.json/tsconfig.json file created be sure to add it to the root of your project. Also, you will need to restart your dev server in order to see these changes.

Now can remove the ../../ and have a much cleaner import.

import SiteNav from 'components/common'
export default ()=> {
    <SiteNav />
}

One nice part is that the old imports will still work.

If your project has a more complex structure you can even declare module aliases. For example, you can say that all the files from the components/ui/buttons directory are mapped to @/buttons:

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

And after just use this alias in your js files:

import MyButton from '@/buttons/MyButton'

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X