typescripteslint

eslint complains about typescript's path aliasing


I've set up path aliasing in typescript's .tsconfig so my imports look cleaner.

In my code when I try and import my interface like this

import { ApiResponse } from '@api';

eslint complains: Unable to resolve path to module '@api' However, intelisense in vscode seems fine. Its able to give code prediction and "Jump to declaration" which is a clue that my .tsconfig is set up correctly but eslint is somehow misconfigured.


Relevant files

In my tsconfig.json, I've set up path aliasing like so:

{
  "compilerOptions": {
    "moduleResolution": "node",               
    "baseUrl": "./src",                     
    "paths": {                              
      "@api": ["./types/api"]
    },
  }
}

My ./src/types/api.ts looks like this:

// 3rd party API response object
export interface ApiResponse {
  ....
}

Finally, my .eslintrc.json looks like this:

{
  "env": {
    "node": true
  },
  "globals": {
    "console": true
  },
  "plugins": ["@typescript-eslint", "prettier"],
  "parser": "@typescript-eslint/parser",
  "settings": {
    "import/extensions": [".js", ".ts"],
    "import/parsers": {
      "@typescript-eslint/parser": [".ts"]
    },
    "import/resolver": {
      "node": {
        "extensions": [".js", ".ts"]
      }
    }
  }
}


Any idea what I may be doing wrong?


Solution

  • To support the tsconfig baseUrl and paths, you need the package eslint-import-resolver-typescript.

    1. Make sure to have the basics:
    # install the basics
    npm i -D @typescript-eslint/parser @typescript-eslint/eslint-plugin
    
    # support tsconfig baseUrl and paths
    npm i -D eslint-plugin-import eslint-import-resolver-typescript
    
    1. Then in the eslintrc, here in json:
    {
      "settings": {
        "import/resolver": {
          "typescript": {}
        }
      },
      "parser": "@typescript-eslint/parser",
      "parserOptions": {
        "project": "./tsconfig.json",
        "tsconfigRootDir": "./"
      },
      "plugins": [
        "@typescript-eslint",
        "import"
      ],
      "extends": [
        "plugin:@typescript-eslint/recommended",
        "plugin:@typescript-eslint/recommended-requiring-type-checking"
      ]
    }