8

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

gayathrithedev
  • 327
  • 2
  • 10

4 Answers4

8

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'
gayathrithedev
  • 327
  • 2
  • 10
5

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

GorvGoyl
  • 42,508
  • 29
  • 229
  • 225
1

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/*"],
}
Lazar Nikolov
  • 928
  • 14
  • 21
0

I was not able to solve the problem by the means described above.

However, we were able to solve the problem using the following library.

https://www.npmjs.com/package/eslint-import-resolver-alias

npm install eslint-plugin-import eslint-import-resolver-alias --save-dev

jsconfig.json

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

.eslintrc.json

{
...
  "settings": {
    "import/resolver": {
      "alias": {
        "map": [["@", "./src"]],
        "extensions": [".ts", ".js", ".jsx", ".json"]
      }
    }
  }
}

import example

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

to

import Header from '@/components/Header';