创建React应用程序 - 不使用TypeScript,出现错误:无法加载解析器'@typescript-eslint/parser'。

19

我有一个React应用程序的样本安装,并且我遇到了以下问题

Error: Failed to load parser '@typescript-eslint/parser' declared in '.eslintrc » eslint-config-react-app#overrides[0]': Cannot find module 'typescript' 

运行后

 npm run lint -> eslint .

我在这个项目中没有使用TypeScript。 我尝试从头安装它,又遇到了问题。 还尝试从VSCode插件中删除TSLint。


npm install @typescript-eslint/parser typescript - Amir Rezvani
GH问题在这里:https://github.com/facebook/create-react-app/issues/8936 - Vanuan
8个回答

28

1
看起来确实是事实,使用当前处理TypeScript的“overrides”的eslint .意味着node_modules也会对.ts/.tsx文件进行lint。这个PR被提出来解决它:https://github.com/facebook/create-react-app/pull/9310使用:"lint": "eslint --ignore-path .gitignore .",也可以工作,因为默认的.gitignore忽略了node_modules,并且意味着不必维护单独的.eslintignore。 - glenrothes

7

今天尝试创建新的React应用程序时,我遇到了同样的问题。

您可以尝试以下步骤:

  1. 确保更新您的Node.js至最新版本
  2. 确保您的文件夹路径短不包含空格
  3. 运行:npm install -g create-react-app
  4. 运行:npm i --save-dev typescript @typescript-eslint/parser
  5. 运行:create-react-app my-app

在一个使用了craco-extended的项目中遇到了这个问题。npm i --save-dev typescript @typescript-eslint/parser解决了我的问题。谢谢! - spencer741

4

Create React App 会在 package.json 中添加 eslint 的配置,因此只需在 package.json 中添加 eslintIgnore 并将其设置为 node_modules,就可以避免使用独立的文件 .eslintignore

  // package.json
  // ...
  "eslintConfig": {
    "extends": "react-app"
  },
  "eslintIgnore": [
    "node_modules",
    "build/*"
  ],

1
很可能,您在您的.eslintrc文件中有这个内容:
extends: react-app

这句话的意思是:“应用以下规则:”,其中保留了HTML格式,不做解释。
files: ['**/*.ts?(x)'], 
parser: '@typescript-eslint/parser', 

这可能意味着您的根目录中有*.ts/*.tsx文件。但也有可能是vscode-eslint的问题。您尝试从终端运行yarn lint了吗?

0
我正在从一个项目中移除 TypeScript,但由于我忘记了在 src 文件夹下某个地方有一个 TypeScript 定义,所以出现了相同的错误... 删除该文件解决了问题。

0

你的错误信息显示 eslint 正在寻找 TypeScript,因为 .eslintrc 文件中有一个设置,请尝试查看该文件中的 @typescript-eslint/parser 并将其删除。


0
在我的情况下,我不小心运行了yarn.dev而不是npm start,所以我删除了yarn.lock文件和由此产生的yarn错误日志文件。

0
在我的情况下,我想要使用TypeScript,但是没有安装它。 这个问题仍然帮助我解决了我的问题,问题描述如下。
我正在观看一个YouTube视频,React TypeScript教程,该视频解释了如何开始使用TypeScript和React,并且视频中说要运行:
npx create-react-app cra-ts --typescript

这个不起作用(但我不知道)。当我创建了一个hello.ts文件后,我得到了OP描述的错误。

Error: Failed to load parser '@typescript-eslint/parser' declared in 'package.json » eslint-config-react-app#overrides[0]': Cannot find module 'typescript'

解决方法是使用以下命令:
npx create-react-app myappts --template typescript

这里使用的是 create-react-app@4.0.0 和 react-scripts@4.0.0 版本。

专业提示:如果你新创建的 React 应用没有一个名为 App.tsx 的文件,那么你实际上并未正确创建它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接