eslint配置

157 阅读2分钟

基本概念

ESLint 是一个可配置的 JavaScript 检查器。它可以帮助你发现并修复 JavaScript 代码中的问题。问题可以指潜在的运行时漏洞、未使用最佳实践、风格问题等。

配置参数

root

{
  root:true
}

extends

eslint官方拓展

{
  extends:["eslint:recommended", "eslint:all"]
}

注:例如,考虑到 projectA 在 lib/ 目录下的 .eslintrc 文件中设置了 "root": true 在这种情况下,当对 lib/main.js 进行检查时,lib/ 中的配置将被使用,但 projectA/ 中的 .eslintrc 文件不会被使用。

home
└── user
    └── projectA
        ├── .eslintrc.json  <- Not used
        └── lib
            ├── .eslintrc.json  <- { "root": true }
            └── main.js
  • eslint:recommended(推荐规范)
  • eslint:all(所有规范)

关键代码:@eslint/js

eslint-config(共享配置)

  • eslint-config-airbnb(airbnb的规范)
{
  extends:["airbnb"] // extends:["eslint-config-airbnb"]
}

eslint使用可共享配置

eslint-plugin(插件)

  • eslint-plugin-react
{
  extends:["plugin:react/recommended"] 
}

关键代码:eslint-plugin-react

plugin

  • eslint-plugin-react
{
  plugin:["react"]
}

关键代码:eslint-plugin-react

rules

rules文档

{
  "rules": {
    "my-rule": ["error", { "maxLength": 120 }]
  }
}

module.exports = {
  meta: {
    type: "suggestion",
    docs: {
      description: "Enforce a maximum length",
      category: "Stylistic Issues",
      recommended: false
    },
    schema: [
      {
        type: "object",
        properties: {
          maxLength: {
            type: "number"
          }
        },
        additionalProperties: false
      }
    ]
  },
  create: function(context) {
    const maxLength = context.options[0] && context.options[0].maxLength || 80;
    return {
      // Your rule logic using the maxLength option
    };
  }
};

插件规则

插件规则

parser

config parser

@balel/eslint-parser

doc

特别注意:requireConfigFile

parserOption

@typescript-eslint/parser

为啥需要使用:tsc 在处理 ts 语法转译后的 ast 规则是 eslint 默认的 espree 是完全不一致的,所以我们需要通过 @typescript-eslint/parser 解析器来解析我们的代码。 当我们使用特定的解析器时,比如使用 @typescript-eslint/parser 最终会将 ts 文件转移后的 ast 结构转化成为 espree 支持的 ast 结构进行静态检查。

注:plugin:@typescript-eslint/recommended-type-checked

env

Specifying Environments

{
  env: { 
    browser: true,
    node: true,
  },
}

globals

指定全局变量

{
    "globals": {
        "var1": "writable",
        "var2": "readonly"
    }
}

overrides

overides doc

settings

{
  "settings": {
    "sharedKey": "sharedValue"
  }
}

module.exports = {
  rules: {
    "my-rule": {
      create(context) {
        const sharedValue = context.settings.sharedKey;
        // 现在你可以在这里使用共享设置
      },
    },
  },
};

参考