使用 Prettier Eslint 时找不到模块“@typescript-eslint/parser”

问题描述

保存文件时,我从 VSCode 上的 Prettier Eslint 输出中收到以下错误

Error: Cannot find module '@typescript-eslint/parser'
Require stack:
- c:\Users\vtnor\.vscode\extensions\rvest.vs-code-prettier-eslint-0.4.1\dist\extension.js
- c:\Program Files\Microsoft VS Code\resources\app\out\vs\loader.js
- c:\Program Files\Microsoft VS Code\resources\app\out\bootstrap-amd.js
- c:\Program Files\Microsoft VS Code\resources\app\out\bootstrap-fork.js

我的包json是:

[...]
"typescript": "^4.2.2","@typescript-eslint/eslint-plugin": "^4.16.1","@typescript-eslint/parser": "^4.16.1","eslint": "^7.21.0","prettier": "^2.2.1","prettier-eslint": "^12.0.0",[...]

解决方法

我前几天确实遇到了这个问题,你需要去你的.eslintrc 并确保该模块位于配置的 parser 属性下...最终应该是这样的:

{
  //...

  "extends": [
    "eslint:recommended","plugin:@typescript-eslint/eslint-recommended","plugin:@typescript-eslint/recommended","prettier/@typescript-eslint","plugin:prettier/recommended"
  ],"parser": "@typescript-eslint/parser","plugins": [
    "@typescript-eslint"
  ],//...
}

这应该涵盖有关 linter 中依赖项的基本知识...希望对您有所帮助

编辑

我检查了 git hub 是否存在此问题,可能与我的问题不同,请检查此链接https://github.com/prettier/prettier-vscode/issues/905

,

问题可能是 .eslintrc 没有找到必要的模块,因为它们位于错误的位置。 .eslintrc 需要在它旁边有文件夹 node_modules。这可以通过将 .eslintrc 放入项目文件夹并在其旁边创建 package.json 来轻松实现。然后还将在项目文件夹中创建 node_modules,并找到必要的(和已安装的)模块。

您的项目文件夹应类似于:

content of project folder

,

我发现在我的案例中错误的原因是 ESLint 本身抛出了一个错误。我通过查看 VSCode 中的 ESLint 输出发现了这一点。修复是更新我的其他依赖项之一(eslint-plugin-import)。