ESLint.config.mjs中TypeScript规则生效但插件不生效的配置问题
解决eslint.config.mjs中多插件配置失效的问题
你的配置存在几个关键问题,调整后即可让html、react、jest-dom插件正常工作:
1. 修正笔误
配置里plugins对象中的jesdom是拼写错误,应该改为jestdom。
2. 启用插件的内置规则集
大部分ESLint插件都提供了预设规则集,需要像引入typescript-eslint的strict/stylistic一样,将这些预设展开到配置数组中。
3. 配置文件匹配与环境
不同插件对应不同类型的文件,需要针对性设置文件匹配范围,同时为React、Jest等配置对应的运行环境。
正确的配置示例
import html from "eslint-plugin-html"; import tslint from "typescript-eslint"; import react from "eslint-plugin-react"; import jestdom from "eslint-plugin-jest-dom"; import jest from "eslint-plugin-jest"; // 配合jest-dom需额外引入该插件 export default [ // 基础TypeScript规则 ...tslint.configs.strict, ...tslint.configs.stylistic, // HTML插件配置:处理.html文件,启用推荐规则 { files: ["**/*.html"], plugins: { html }, rules: { ...html.configs.recommended.rules, // 自定义HTML规则 } }, // React插件配置:处理.jsx/.tsx文件,启用推荐规则 { files: ["**/*.{jsx,tsx}"], plugins: { react }, settings: { react: { version: "detect" // 自动检测项目中React版本 } }, env: { browser: true, es2021: true }, rules: { ...react.configs.recommended.rules, ...react.configs["jsx-runtime"].rules, // 适配React 17+自动JSX runtime // 自定义React规则 } }, // Jest-Dom插件配置:处理测试文件,启用推荐规则 { files: ["**/*.{test,spec}.{js,jsx,ts,tsx}"], plugins: { jest, jestdom }, env: { jest: true, browser: true // jest-dom依赖浏览器环境 }, rules: { ...jest.configs.recommended.rules, ...jestdom.configs.recommended.rules, // 自定义Jest规则 } }, // 全局自定义规则 { rules: { // 你的全局自定义规则 } } ];
关键说明
- 文件匹配(files字段):通过
files指定插件作用的文件范围,避免规则误应用到不相关文件上。 - 插件规则集:使用
...插件.configs.xxx.rules的方式引入预设规则,无需手动逐个开启。 - React配置:
settings.react.version设为detect可自动读取项目React版本,jsx-runtime规则适配React 17+无需手动引入React的场景。 - Jest-Dom依赖:jest-dom插件需要配合eslint-plugin-jest使用,确保已安装该依赖。
内容的提问来源于stack exchange,提问作者Ar26
相关产品推荐
相关产品推荐

