基本概念
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-plugin(插件)
eslint-plugin-react
{
extends:["plugin:react/recommended"]
}
关键代码:eslint-plugin-react
plugin
eslint-plugin-react
{
plugin:["react"]
}
关键代码:eslint-plugin-react
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
@balel/eslint-parser
特别注意:
requireConfigFile
@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
{
env: {
browser: true,
node: true,
},
}
globals
{
"globals": {
"var1": "writable",
"var2": "readonly"
}
}
overrides
settings
{
"settings": {
"sharedKey": "sharedValue"
}
}
module.exports = {
rules: {
"my-rule": {
create(context) {
const sharedValue = context.settings.sharedKey;
// 现在你可以在这里使用共享设置
},
},
},
};