eslint 抱怨打字稿的路径别名 [英] eslint complains about typescript's path aliasing

查看:96
本文介绍了eslint 抱怨打字稿的路径别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 typescript 的 .tsconfig 中设置了路径别名,所以我的导入看起来更干净.

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 抱怨:无法解析模块@api"的路径但是,vscode 中的智能感知似乎很好.它能够提供代码预测和跳转到声明",这是我的 .tsconfig 设置正确但 eslint 不知何故配置错误的线索.

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.

在我的 tsconfig.json 中,我像这样设置了路径别名:

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

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

我的 ./src/types/api.ts 看起来像这样:

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

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

最后,我的 .eslintrc.json 看起来像这样:

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


知道我做错了什么吗?

推荐答案

要支持 tsconfig baseUrlpaths,您需要包 eslint-import-resolver-typescript.

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

  1. 确保具备基础知识:

# 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. 然后在 eslintrc 中,在 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"
  ]
}

这篇关于eslint 抱怨打字稿的路径别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆