在ESLint的实际使用过程中,我们经常会引入各类插件来扩展检查能力,但很多插件包含大量规则,全部启用会增加配置复杂度,也不符合项目的实际需求。只需要启用插件的单个规则是更合理的选择,下面介绍具体的实现方法。

ESLint 插件规则的基本配置逻辑
ESLint的插件规则命名格式为插件名/规则名,要启用单个插件规则,需要在配置文件的rules字段中单独声明该规则,同时不需要在extends字段中引入插件的所有规则集。
基础配置示例
以常用的eslint-plugin-react插件为例,假设我们只需要启用其中的react/prop-types规则,配置方式如下:
{
"plugins": ["react"],
"rules": {
"react/prop-types": ["warn", { "ignore": ["children"] }]
}
}
上述配置中,plugins数组声明了要使用的插件,rules字段中仅添加了react/prop-types这一条规则,规则的值第一个元素是错误级别,可选值为off、warn、error,后面的对象是该规则的自定义配置项。
不同配置文件类型的写法
JavaScript 格式配置文件(.eslintrc.js)
如果使用JavaScript格式的配置文件,写法如下:
module.exports = {
plugins: ['react'],
rules: {
'react/prop-types': ['error', {
// 允许组件没有定义children的prop类型
ignore: ['children']
}]
}
};
YAML 格式配置文件(.eslintrc.yaml)
YAML格式的配置文件写法如下:
plugins:
- react
rules:
react/prop-types:
- warn
- ignore:
- children
验证配置是否生效
配置完成后,可以创建一个测试文件来验证规则是否仅启用了目标规则。例如创建一个test.jsx文件:
import React from 'react';
// 没有定义prop-types,应该触发react/prop-types警告
function TestComponent(props) {
return <div>{props.name}</div>;
}
export default TestComponent;
运行ESLint检查命令:
npx eslint test.jsx
如果配置正确,会输出react/prop-types相关的提示,而不会出现该插件其他规则的报错信息。
注意事项
- 必须先通过
plugins字段声明要使用的插件,否则ESLint无法识别插件名/规则名格式的规则。 - 不要在
extends中加入插件推荐的规则集,比如不要添加plugin:react/recommended,否则会启用插件的所有推荐规则。 - 如果规则需要额外的解析器支持,比如React规则需要
babel-eslint或者@babel/eslint-parser,还需要在配置中声明parser字段。
ESLintESLint_pluginESLint_ruleJavaScript修改时间:2026-06-16 15:39:13