eslint resolve error on imports using with path mapping configured jsconfig.json
Here’s my project structure:
-src
--assets
--components
--constants
--helpers
--pages
--routes
eslintrc.json
jsconfig.json
App.js
index.js
I was tired of:
import SomeComponent from '../../../../../components/SomeComponent';
And I wanted to do:
import SomeComponent from '@components/SomeComponent';
So I saw this question here on SO:
VSCode Intellisense does not work with webpack + alias
And I got it to work with:
jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"target": "es6",
"module": "commonjs",
"paths": {
"@components/*": ["./src/components/*"]
}
}
}
But eslint now it’s complaining that it’s unresolved, even though it compiles just fine.
eslint error:
Unable to resolve path to module ‘@components/SocialMedia’.eslint(import/no-unresolved)
NOTE:
I don’t want to disable eslint. I want to make it understand this kind of path too.
An alternative way, assuming that you have eslint-plugin-import
installed (in your devDependencies). Just add this “settings” in your .eslintrc.json
file.
.eslintrc.json
{
"settings": {
"import/resolver": {
"node": {
"moduleDirectory": ["node_modules", "src/"]
}
}
}
}
jsconfig.json
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
Then you can just call the
import SomeComponent from 'components/SomeComponent';`
I have installed:
npm install -D eslint-import-resolver-alias
And I added to my eslint config file:
eslintrc.json
"settings": {
"import/resolver" : {
"alias" : {
"map" : [
["@components","./src/components/"]
],
"extensions": [".js"]
}
}
}
And now it’s working and eslint is not showing errors anymore.
EDIT:
I’m using webpack and I also needed to do:
webpack.config.js
resolve: {
alias: {
'@components': path.resolve(__dirname, 'src/components/')
}
}
for lerna users:
eslintrc
{
"settings": {
"import/parsers": {
"@typescript-eslint/parser": [".js", ".jsx", ".ts", ".tsx"]
},
"import/resolver": {
"node": {
"extensions": [".js", ".jsx", ".ts", ".tsx"],
// this resolves path alias import problems
"moduleDirectory": [ "apps/*/src", "packages/*/src" ]
},
"typescript": {
"alwaysTryTypes": true,
// this resolves packages import problems
"project": [
"packages/*/tsconfig.json",
"apps/*/tsconfig.json"
]
}
}
}
}