eslint 常用配置

前言

在团队协作开发中,为了统一代码风格,避免一些低级错误,应该设有团队成员统一遵守的编码规范。很多语言都提供了Lint工具来实现这样的功能,JavaScript也有类似的工具:ESLint。除了可以集成到构建工具中(如:Gulp)在构建过程中检查代码风格以外;还可以通过将ESLint和代码编辑器相结合以提供代码风格的实时校验。这里将介绍如何在Visual Studio Code使用ESLint来提供代码风格的实时校验。

配置原则

  1. 能够帮助发现代码错误的规则,全部开启
  2. 配置不应该依赖于某个具体项目,而应尽可能的合理
  3. 帮助保持团队的代码风格统一,而不是限制开发体验

配置解读

  1. 每一条配置都有注释说明此配置的用途
  2. 对于理解困难的配置,都在注释中有举例
  3. 对于有争议的配置,都在注释中说明了为什么要这么配置的原因
  4. 对于关闭掉的配置,都在注释中有对应的原因说明,以及 @off 的标识
  5. 对于能够 autofix 的配置,都在注释中有标注 @autofix

EsLint提供以下支持:

  1. ES6
  2. AngularJS
  3. JSX
  4. Style检查
  5. 自定义错误和提示

EsLint提供以下几种校验:

1.语法错误校验
2.不重要或丢失的标点符号,如分号
3.没法运行到的代码块(使用过WebStorm的童鞋应该了解)
4.未被使用的参数提醒
5.漏掉的结束符,如}
6.确保样式的统一规则,如sass或者less
7.检查变量的命名

详细的配置内容在这里:

/**
 * AlloyTeam ESLint 规则 - React
 *
 * 包含所有 ESLint 规则,以及所有 eslint-plugin-react 规则
 * 使用 babel-eslint 作为解析器
 *
 * @fixable 表示此配置支持 --fix
 * @off 表示此配置被关闭了,并且后面说明了关闭的原因
 */

module.exports = {
    extends: [
        './index.js',
    ],
    plugins: [
        'react'
    ],
    rules: {
        // 布尔值类型的 propTypes 的 name 必须为 is 或 has 开头
        // @off 不强制要求写 propTypes
        'react/boolean-prop-naming': 'off',
        // 一个 defaultProps 必须有对应的 propTypes
        // @off 不强制要求写 propTypes
        'react/default-props-match-prop-types': 'off',
        // 组件必须有 displayName 属性
        // @off 不强制要求写 displayName
        'react/display-name': 'off',
        // 禁止在自定义组件中使用一些指定的 props
        // @off 没必要限制
        'react/forbid-component-props': 'off',
        // 禁止使用一些指定的 elements
        // @off 没必要限制
        'react/forbid-elements': 'off',
        // 禁止使用一些指定的 propTypes
        // @off 不强制要求写 propTypes
        'react/forbid-prop-types': 'off',
        // 禁止直接使用别的组建的 propTypes
        // @off 不强制要求写 propTypes
        'react/forbid-foreign-prop-types': 'off',
        // 禁止使用数组的 index 作为 key
        // @off 太严格了
        'react/no-array-index-key': 'off',
        // 禁止使用 children 做 props
        'react/no-children-prop': 'error',
        // 禁止使用 dangerouslySetInnerHTML
        // @off 没必要限制
        'react/no-danger': 'off',
        // 禁止在使用了 dangerouslySetInnerHTML 的组建内添加 children
        'react/no-danger-with-children': 'error',
        // 禁止使用已废弃的 api
        'react/no-deprecated': 'error',
        // 禁止在 componentDidMount 里面使用 setState
        // @off 同构应用需要在 didMount 里写 setState
        'react/no-did-mount-set-state': 'off',
        // 禁止在 componentDidUpdate 里面使用 setState
        'react/no-did-update-set-state': 'error',
        // 禁止直接修改 this.state
        'react/no-direct-mutation-state': 'error',
        // 禁止使用 findDOMNode
        'react/no-find-dom-node': 'error',
        // 禁止使用 isMounted
        'react/no-is-mounted': 'error',
        // 禁止在一个文件创建两个组件
        // @off 有一个 bug https://github.com/yannickcr/eslint-plugin-react/issues/1181
        'react/no-multi-comp': 'off',
        // 禁止在 PureComponent 中使用 shouldComponentUpdate
        'react/no-redundant-should-component-update': 'error',
        // 禁止使用 ReactDOM.render 的返回值
        'react/no-render-return-value': 'error',
        // 禁止使用 setState
        // @off setState 很常用
        'react/no-set-state': 'off',
        // 禁止拼写错误
        'react/no-typos': 'error',
        // 禁止使用字符串 ref
        'react/no-string-refs': 'error',
        // 禁止在组件的内部存在未转义的 >, ", ' 或 }
        'react/no-unescaped-entities': 'error',
        // @fixable 禁止出现 HTML 中的属性,如 class
        'react/no-unknown-property': 'error',
        // 禁止出现未使用的 propTypes
        // @off 不强制要求写 propTypes
        'react/no-unused-prop-types': 'off',
        // 定义过的 state 必须使用
        // @off 没有官方文档,并且存在很多 bug: https://github.com/yannickcr/eslint-plugin-react/search?q=no-unused-state&type=Issues&utf8=%E2%9C%93
        'react/no-unused-state': 'off',
        // 禁止在 componentWillUpdate 中使用 setState
        'react/no-will-update-set-state': 'error',
        // 必须使用 Class 的形式创建组件
        'react/prefer-es6-class': [
            'error',
            'always'
        ],
        // 必须使用 pure function
        // @off 没必要限制
        'react/prefer-stateless-function': 'off',
        // 组件必须写 propTypes
        // @off 不强制要求写 propTypes
        'react/prop-types': 'off',
        // 出现 jsx 的地方必须 import React
        // @off 已经在 no-undef 中限制了
        'react/react-in-jsx-scope': 'off',
        // 非 required 的 prop 必须有 defaultProps
        // @off 不强制要求写 propTypes
        'react/require-default-props': 'off',
        // 组件必须有 shouldComponentUpdate
        // @off 没必要限制
        'react/require-optimization': 'off',
        // render 方法中必须有返回值
        'react/require-render-return': 'error',
        // @fixable 组件内没有 children 时,必须使用自闭和写法
        // @off 没必要限制
        'react/self-closing-comp': 'off',
        // @fixable 组件内方法必须按照一定规则排序
        'react/sort-comp': 'error',
        // propTypes 的熟悉必须按照字母排序
        // @off 没必要限制
        'react/sort-prop-types': 'off',
        // style 属性的取值必须是 object
        'react/style-prop-object': 'error',
        // HTML 中的自闭和标签禁止有 children
        'react/void-dom-elements-no-children': 'error',
        // @fixable 布尔值的属性必须显式的写 someprop={true}
        // @off 没必要限制
        'react/jsx-boolean-value': 'off',
        // @fixable 自闭和标签的反尖括号必须与尖括号的那一行对齐
        'react/jsx-closing-bracket-location': [
            'error',
            {
                nonEmpty: false,
                selfClosing: 'line-aligned'
            }
        ],
        // @fixable 结束标签必须与开始标签的那一行对齐
        // @off 已经在 jsx-indent 中限制了
        'react/jsx-closing-tag-location': 'off',
        // @fixable 大括号内前后禁止有空格
        'react/jsx-curly-spacing': [
            'error',
            {
                when: 'never',
                attributes: {
                    allowMultiline: true
                },
                children: true,
                spacing: {
                    objectLiterals: 'never'
                }
            }
        ],
        // @fixable props 与 value 之间的等号前后禁止有空格
        'react/jsx-equals-spacing': [
            'error',
            'never'
        ],
        // 限制文件后缀
        // @off 没必要限制
        'react/jsx-filename-extension': 'off',
        // @fixable 第一个 prop 必须得换行
        // @off 没必要限制
        'react/jsx-first-prop-new-line': 'off',
        // handler 的名称必须是 onXXX 或 handleXXX
        // @off 没必要限制
        'react/jsx-handler-names': 'off',
        // @fixable jsx 的 children 缩进必须为四个空格
        'react/jsx-indent': [
            'error',
            4
        ],
        // @fixable jsx 的 props 缩进必须为四个空格
        'react/jsx-indent-props': [
            'error',
            4
        ],
        // 数组中的 jsx 必须有 key
        'react/jsx-key': 'error',
        // @fixable 限制每行的 props 数量
        // @off 没必要限制
        'react/jsx-max-props-per-line': 'off',
        // jsx 中禁止使用 bind
        // @off 太严格了
        'react/jsx-no-bind': 'off',
        // 禁止在 jsx 中使用像注释的字符串
        'react/jsx-no-comment-textnodes': 'error',
        // 禁止出现重复的 props
        'react/jsx-no-duplicate-props': 'error',
        // 禁止在 jsx 中出现字符串
        // @off 没必要限制
        'react/jsx-no-literals': 'off',
        // 禁止使用 target="_blank"
        // @off 没必要限制
        'react/jsx-no-target-blank': 'off',
        // 禁止使用未定义的 jsx elemet
        'react/jsx-no-undef': 'error',
        // 禁止使用 pascal 写法的 jsx,比如 <TEST_COMPONENT>
        'react/jsx-pascal-case': 'error',
        // @fixable props 必须排好序
        // @off 没必要限制
        'react/jsx-sort-props': 'off',
        // @fixable jsx 的开始和闭合处禁止有空格
        'react/jsx-tag-spacing': [
            'error',
            {
                closingSlash: 'never',
                beforeSelfClosing: 'always',
                afterOpening: 'never'
            }
        ],
        // jsx 文件必须 import React
        'react/jsx-uses-react': 'error',
        // 定义了的 jsx element 必须使用
        'react/jsx-uses-vars': 'error',
        // @fixable 多行的 jsx 必须有括号包起来
        // @off 没必要限制
        'react/jsx-wrap-multilines': 'off'
    }
};

使用方法

标准规则
安装
npm install --save-dev eslint-config-alloy babel-eslint

配置 .eslintrc.js

在你的项目根目录下创建 .eslintrc.js,并将以下内容复制到文件中:

module.exports = {  
    extends: [
        'eslint-config-alloy',
    ],
    globals: {
        // 这里填入你的项目需要的全局变量
        // 这里值为 false 表示这个全局变量不允许被重新赋值,比如:
        //
        // jQuery: false,
        // $: false
    },
    rules: {
        // 这里填入你的项目需要的个性化配置,比如:
        //
        // // @fixable 一个缩进必须用两个空格替代
        // 'indent': [
        //     'error',
        //     2,
        //     {
        //         SwitchCase: 1,
        //         flatTernaryExpressions: true
        //     }
        // ]
    }
};
React 版

安装

npm install --save-dev eslint-config-alloy eslint-plugin-react babel-eslint

配置 .eslintrc.js

在你的项目根目录下创建 .eslintrc.js,并将以下内容复制到文件中:

安装完成后我们可以看到除了ESLint命令行工具为我们生成的ESLint依赖包,还有一个特殊的.eslintrc.json文件,该文件是ESLint的配置文件,如下所示:

{
    "extends": "standard",
    "installedESLint": true,
    "plugins": [
        "standard"
    ]
}

配置文件中除了声明我们所使用的代码风格以外,我们还可以定制自己的规则,比如:声明全局变量或者规定字符串引号的风格,以及其他任何ESLint支持的规则都是可以配置的,下面是一个简单的示例:

{
    "extends": "standard",
    "installedESLint": true,
    "plugins": [
        "standard"
    ],
    "rules": {
        //关闭额外的分号检查
        //0:关闭,1:警告,2:异常
        "semi": 0,
        //字符串必须使用单引号
        "quotes": [
            "error",
            "single"
        ]
    }
}

配置文件中除了声明我们所使用的代码风格以外,我们还可以定制自己的规则,比如:声明全局变量或者规定字符串引号的风格,以及其他任何ESLint支持的规则都是可以配置的,下面是一个简单的示例:

module.exports = {
    extends: [
        'eslint-config-alloy/react',
    ],
    globals: {
        // 这里填入你的项目需要的全局变量
        // 这里值为 false 表示这个全局变量不允许被重新赋值,比如:
        //
        // React: false,
        // ReactDOM: false
    },
    rules: {
        // 这里填入你的项目需要的个性化配置,比如:
        //
        // // @fixable 一个缩进必须用两个空格替代
        // 'indent': [
        //     'error',
        //     2,
        //     {
        //         SwitchCase: 1,
        //         flatTernaryExpressions: true
        //     }
        // ],
        // // @fixable jsx 的 children 缩进必须为两个空格
        // 'react/jsx-indent': [
        //     'error',
        //     2
        // ],
        // // @fixable jsx 的 props 缩进必须为两个空格
        // 'react/jsx-indent-props': [
        //     'error',
        //     2
        // ]
    }
};

代码改造经验

如果是一个新项目,应用一个比较严格的 ESLint 规则并不是一件难事。

但是如果是一个已经维护多年的老项目,那么突然引入 ESLint 就会有成千上万个错误。这个时候该如何改造呢?

1. 将所有报错的配置都关闭

运行 ESLint 之后,会有很多错误,这时候我们可以把他们先暂时关闭掉。

由于项目还在不停地迭代,这样可以保证其他不会报错的规则能够应用到新增的文件上。

这时你的 .eslintrc.js 应该类似与下面的样子:

module.exports = {
    extends: [
        '@alloyteam/eslint-config-standard',
    ],
    globals: {
        React: false,
        jQuery: false,
        $: false
    },
    rules: {
        'no-dupe-keys': 'off',
        'no-var': 'off',
        'complexity': 'off',
        'indent': 'off'
    }
};

小技巧:如果报错的规则太多了,可以在运行 ESLint 的时候,加上参数 -f json,这样的话会以 json 格式输出,然后稍作处理就可以直接得到所有报错的规则了。

注意:一开始不要开启 --fix,因为修复的太多了,就难以 review 代码了。

原文地址:https://www.cnblogs.com/Hsong/p/9023341.html