9

I've got a jsconfig.json file in my VS Code:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "allowSyntheticDefaultImports": true,
    "baseUrl": "./src/",
    "paths": {
      "*": ["*"],
      "components/*": ["components/*"]
    }
  },
  "exclude": ["node_modules", "**/node_modules/*"]
}

Having paths helps me to have shorter import statements. My code builds just fine, however how do I tell eslint to respect these settings?

import React from 'react';

export default () => <div>Hello guys</div>;

and my ./src/App.js:

import React from 'react';
import HelloWorld from 'components/HelloWorld';

const App = () => (
  <div className="App">
    <header className="App-header">
      <h1 className="App-title">Welcome to React</h1>
    </header>
    <p className="App-intro">
      To get started, edit <code>src/App.js</code> and save to reload.
    </p>
    <HelloWorld />
  </div>
);

export default App;

However my second line has a red squiggly. How do I configure my eslint to respect jsonfig.json? Disabling this rule would be last resort.

Basically I want to have working absolute imports as in this tutorial: https://itnext.io/create-react-app-with-vs-code-1913321b48d

So that ESLint doesn't complain about it.

Screenshot of my IDE: enter image description here

Evaldas Buinauskas
  • 13,739
  • 11
  • 55
  • 107
  • Just asking because you haven't mentioned it: Have you created the `.env` file at the root directory containing `NODE_PATH=src/` and restarted vscode? Furthermore have you tried to remove the `component/*` entry of your `jsconfig.json`? – HaaLeo Mar 19 '18 at 10:37
  • @HaaLeo I've got `.env` file as you would expect. Why would you want me to remove `component/*` from `jsconfig.json`? I'm not very clear. – Evaldas Buinauskas Mar 19 '18 at 11:11
  • @HaaLeo To be clear. Code builds and webpack understands it, it's just eslint that complains about these... – Evaldas Buinauskas Mar 19 '18 at 11:22
  • Possible duplicate of [How to manually add a path to be resolved in eslintrc](https://stackoverflow.com/questions/41769880/how-to-manually-add-a-path-to-be-resolved-in-eslintrc) – Evaldas Buinauskas Mar 19 '18 at 13:21

2 Answers2

5

install:

npm i -D eslint-import-resolver-webpack eslint-plugin-import

add to .eslintrc:

"settings": {
  "import/resolver": {
   "webpack": {
     "config": "webpack.config.js"
   }
  }
}

add to webpack.config.js:

const path = require('path')

resolve: {
  modules: [
   'node_modules',
   path.resolve('./assets'),  //your path
   path.resolve('./constans'), //your path
]}
Jiml
  • 377
  • 3
  • 9
  • 1
    thanks. BTW my `. eslintrc` looks like JSON format and starts just with `{`, so I should just set only `"import/resolver": { webpack `, without `"settings": {}` – Yury Shapkarin Sep 19 '21 at 15:13
5

Add this to .eslintrc

  "settings": {
    "import/resolver": {
      "node": {
        "paths": ["src"]
      }
    }
  }
cubefox
  • 1,251
  • 14
  • 29