eslint + jsconfig + nextjs module path aliases (absolue path import - @)

Viewed 3489

I am trying to import the files using custom aliases following the nextjs documentation.

My current approach is

from

import Header from '../../../components/Header';

to

import Header from '@components/Header';

I am getting the expected result. But eslint throws the following error:

  • unable to resolve path to module (eslint - import/no unresolved)

And I have tried adding the following line in my eslintrc file to resolve the error

    settings: {
    'import/resolver': {
      node: {
        paths: ['src'],
      },
    },
  },

But still the eslint throws the same error.

What is the correct approach to resolve this one?

Thanks in advance...

Note: I don't want to remove eslint and I need @components import aliases

3 Answers

Finally after digging into lots of GitHub answers and etc...

Inside your eslintrc file... add the following aliases

    settings: {
    'import/resolver': {
      alias: {
        map: [
          ['@components', '../../../components/'],
          ['@images', '../../../assets/images/'],
        ],
        extensions: ['.js', '.jsx'],
      },
    },
  },

and also to fix flow error inside your flowconfig file add the name_mapper

module.name_mapper='^@components' ->'<PROJECT_ROOT>/../../../components'
module.name_mapper='^@images' ->'<PROJECT_ROOT>/../../../assets/images'

You need to also install npm i -D eslint-import-resolver-typescript and then add below to eslint config file:

"settings": {
    "import/resolver": {
      "typescript": {} // this loads <rootdir>/tsconfig.json to eslint
    },
}

Reference: https://gourav.io/blog/nextjs-cheatsheet

You can try adding your custom paths in tsconfig.json/jsconfig.json, like so:

  • Add a baseUrl in your compilerOptions (in my case it's "baseUrl": ".")
  • Add your paths in a paths object:
"paths": {
   "components": ["components/*"],
}
Related