šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

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 *