eslint complains about typescript's path aliasing

Issue

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"
  ]
}

Answered By – Shaun Luttin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published