DEV Community

Cui Mingda
Cui Mingda

Posted on

How to config ESLint rules based on eslint:all

用CRA创建的项目,在package.json中默认会有一个eslintConfig对象,引入CRA的默认ESLint设置:

"eslintConfig": {
  "extends": [
    "react-app",
    "react-app/jest"
  ]
}
Enter fullscreen mode Exit fullscreen mode

在这个基础上,我们可以扩展和覆盖规则,比如这里我们通过eslint:all将所有ESLint的规则引入进来,规则很多,难免有一些规则不符合需要,根据自己的情况做一些修正。

修正规则按照文件扩展名来操作,防止将修改应用到自己不可预知的情况,一个文件可能会匹配多个规则,更加灵活。

"eslintConfig": {
  "extends": [
    "eslint:all",
    "plugin:react/recommended",
    "plugin:react-hooks/recommended",
    "plugin:import/recommended",
    "plugin:jsx-a11y/recommended",
    "plugin:flowtype/recommended",
    "react-app",
    "react-app/jest"
  ],
  "overrides": [
    {
      "files": [
        "**/*.{js,jsx}"
      ],
      "rules": {
      }
    },
    {
      "files": [
        "**/__tests__/**/*",
        "**/*.{spec,test}.*"
      ],
      "rules": {
      }
    }
  ]
},
Enter fullscreen mode Exit fullscreen mode

先是禁用一些规则:不管是排序对象的keys,还是排序imports,实际代码都挺繁杂的,而且没有发现对运行效率的提升;在代码块内部前后都加一个空行,反而影响美观;多个变量设置一个const,很久以前就有的规则,但是会让写代码受到制约。几个规则都会影响开发效率,而不是提升,就去掉了。

"sort-keys": 0,
"sort-imports": 0,
"padded-blocks": 0,
"one-var": 0
Enter fullscreen mode Exit fullscreen mode

将缩紧数量调整为2个空格,默认是4:

"indent": [
  "error",
  2
],
Enter fullscreen mode Exit fullscreen mode

如果对象定义在一行,那么在对象内部保留空格,会增加可读性

"object-curly-spacing": [
  "error",
  "always"
],
Enter fullscreen mode Exit fullscreen mode

padded-blocks相关的另外一条规则,就是代码块之间的空行,默认是2:

"no-multiple-empty-lines": [
  "error",
  {
    "max": 1
  }
]
Enter fullscreen mode Exit fullscreen mode

再有就是涉及到代码自动换行的规则,一个是数组元素,三个以后才多行,这样useState的情况就可以保持一行;另外一个是函数参数,保持一致,要么都换行,要么都在一行。

"array-element-newline": [
  "error",
  {
    "ArrayExpression": "consistent",
    "ArrayPattern": {
      "minItems": 3
    }
  }
],
"function-call-argument-newline": [
  "error",
  "consistent"
]
Enter fullscreen mode Exit fullscreen mode

禁用测试代码函数长度的限制,测试代码本来就是描述行为,尤其是describe函数,就是用来分组用的,很容易超过默认的50行上限。

"max-lines-per-function": 0
Enter fullscreen mode Exit fullscreen mode

Related ESLint Rules

References

Top comments (0)