NestJS项目启用plugin:prettier/recommended时lint报错找不到@typescript-eslint模块
问题场景
项目基于NestJS搭建,使用eslint_d做代码检查,eslint配置文件中启用plugin:prettier/recommended时,执行lint命令会抛出以下错误:
Error: Cannot find module '@typescript-eslint' Require stack: - /.../node_modules/prettier/index.js - /.../node_modules/eslint-plugin-prettier/eslint-plugin-prettier.js - /.../node_modules/@eslint/eslintrc/dist/eslintrc.cjs Occurred while linting /.../xxx.controller.ts:1 Rule: "prettier/prettier"
禁用plugin:prettier/recommended配置项后,eslint_d可正常运行。
解决步骤
重新安装并校验依赖
确保所有相关开发依赖正确安装且版本兼容,执行以下命令:npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-prettier prettier安装完成后,用
npm list @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-prettier prettier检查版本,需保证@typescript-eslint/parser与@typescript-eslint/eslint-plugin版本完全一致。重启eslint_d进程
eslint_d是常驻内存的进程,可能缓存了旧的依赖状态,执行命令重启:eslint_d restart若无效,先停止再启动:
eslint_d stop && eslint_d start清理并重建依赖目录
若node_modules存在损坏或依赖冲突,执行以下操作:rm -rf node_modules package-lock.json npm install校验配置文件路径
确认eslint配置中parserOptions.project指向的tsconfig.json路径正确,可尝试改用绝对路径(需先引入path模块):const path = require('path'); module.exports = { parser: '@typescript-eslint/parser', parserOptions: { project: path.resolve(__dirname, 'tsconfig.json'), tsconfigRootDir: __dirname, sourceType: 'module', }, // ... 其他配置项 }检查版本兼容性
确保eslint-plugin-prettier与prettier版本匹配,@typescript-eslint系列包与项目TypeScript版本兼容,比如eslint-plugin-prettier要求prettier >= 2.0.0,可查看对应包的README确认兼容范围。
内容的提问来源于stack exchange,提问作者Carlos Hurtado

