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:
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
We're going to configure ESLint to allow us to have path aliases and warnings on our code editor when the path is wrong. prettier will help us as a code formatter and I honestly recommend everyone use it! We need to tell eslint which plugins we want to use and which settings we want to configure for each plugin.
These options allow you to configure module aliases, for example a common pattern is aliasing certain directories to use absolute paths. One useful feature of these options is that they integrate automatically into certain editors, for example vscode. The baseUrl configuration option allows you to import directly from the root of the project.
For this TypeScript has the "paths" option. Using "paths" allows you to configure module aliases. For example @/components/* to components/*. An example of this configuration:
Left side of the tuple is your alias, on the right side is where the alias should map to. In this case, @ resolves to the root folder . This is for the production build. Since nextJS uses webpack to build everything for production, we need to configure the resolver and tell webpack how to read our imports.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With