React项目配置Eslint+Airbnb规则时报错无法加载@babel/eslint-parser
排查解决步骤
- 第一步:补全依赖并重建依赖缓存
@babel/eslint-parser要求必须安装同版本的@babel/core作为核心依赖,你之前的安装命令遗漏了该依赖,是最常见的报错原因。先删除项目根目录下的node_modules文件夹和锁文件(package-lock.json/yarn.lock/pnpm-lock.yaml),执行以下命令重新安装所有依赖:
# 清理旧依赖 rm -rf node_modules package-lock.json # 安装项目基础依赖 npm install # 安装eslint所需babel相关依赖 npm install @babel/core @babel/eslint-parser @babel/preset-react -D
第二步:调整ESLint配置文件位置
你的报错提示配置文件路径为src\.eslintrc.js,说明你把配置文件放在了src子目录中,这会导致ESLint默认从src目录向上查找依赖,找不到根目录的node_modules里的安装包。把.eslintrc.js移动到项目根目录(和package.json同级)即可解决路径问题。第三步:修复VS Code ESLint插件配置
如果命令行执行npx eslint [你的测试文件路径]没有报错,仅VS Code提示报错,按以下操作修复:
- 按
Ctrl+Shift+P(Mac系统为Cmd+Shift+P)唤起命令面板,执行ESLint: Restart ESLint Server重启ESLint服务 - 如果重启后仍报错,打开VS Code的
settings.json,添加以下配置指定ESLint工作目录:
{ "eslint.workingDirectories": ["./"] }
- 可选适配:TypeScript项目调整
如果你的项目使用TypeScript开发,不需要使用@babel/eslint-parser,替换为TS专属解析器即可解决类型标注报错:
- 安装对应依赖
npm install @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-import-resolver-typescript -D
- 修改
.eslintrc.js配置:
module.exports = { extends: ["airbnb", "airbnb-typescript", "prettier"], plugins: ["prettier", "@typescript-eslint"], parser: "@typescript-eslint/parser", parserOptions: { project: "./tsconfig.json" }, rules: { "prettier/prettier": ["error"], "react/jsx-filename-extension": ["off"], "react/prefer-stateless-function": ["off"], "import/extensions": ["off"], "import/no-unresolved": ["off"], "indent": ["error", 2] } };
内容的提问来源于stack exchange,提问作者user17450307
相关产品推荐
相关产品推荐

