Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of 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'
Home Screencasts Best of Newsletter Search X