How to change eslint settings to understand absolute import?

Alexander Knyazev picture Alexander Knyazev · May 8, 2018 · Viewed 14.5k times · Source

I use create-react-app and I want to use absolute import from ./src.

As Dan Abramov recommended I added .env with NODE_PATH=src and it works.

But my eslint doesn't understand that module already exists. I get error import/no-unresolved and import/extensions

This is my eslint-config:

module.exports = {
parser: 'babel-eslint',
extends: 'airbnb',
rules: {
    'react/no-did-mount-set-state': 'off',
    'import/no-extraneous-dependencies': 'off',
    'no-use-before-define': 'off',
    'arrow-body-style': 'off',
    // uncommit on developing
    'no-console': 'off',
    'no-debugger': 'off',
  },
  globals: {
    browser: true,
    fetch: true,
    serviceworker: true,
    describe: true,
    it: true,
    expect: true,
    document: true,
  },

};

And of course it will good if vscode will make suggests for me by 'src'.

Answer

Guillaume Jasmin picture Guillaume Jasmin · May 8, 2018

You need to use eslint-plugin-import: https://github.com/benmosher/eslint-plugin-import

And configure your eslint settings in .eslintrc

module.exports = {
  ...   
  "settings": {
    "import/resolver": {
      "node": {
        "paths": ["src"]
      }
    },
  },
}

Then, you can use import from src folder.

Example, if you have src/components/MyComponent.jsx, you will write this:

import MyComponent from 'components/MyComponent.jsx';