个人博客 个人博客
首页
  • 前端
  • 后端
  • Git
  • Docker
  • 网络
  • 操作系统
工具
阅读
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

董先亮

前端react开发
首页
  • 前端
  • 后端
  • Git
  • Docker
  • 网络
  • 操作系统
工具
阅读
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • homebrew
  • yarn
  • npm
  • eslint
    • 介绍
    • 安装
    • 使用
      • 初始化一个项目
      • 常用命令
    • 配置
      • env
      • parser
      • parserOptions
      • vue需单独配置parser
      • overrides
      • plugins
      • extends
      • rules
      • globals
    • 配置文件优先级
    • 常用插件
    • 相关链接
  • prettier
  • lint-staged
  • pretty-quick
  • husky
  • commitlint
  • pnpm
  • npx
  • vite
  • git
  • iTerm配置
  • Mac常见问题
  • 工具
NeverStop1024
2022-08-30
目录

eslint

# 介绍

ESLint 是一个开源的 JavaScript 的代码检查工具,使用 espree 将代码解析为抽象语法书(AST),通过 AST 进行静态代码分析,并给予代码格式和代码质量两个方面的提示:

  1. 代码格式(Formatting rules):Tab 长度、函数最大行数、尾随分号等
  2. 代码质量(Code-quality rules):未使用的变量、使用到了保留字、全局变量的污染等问题。

# 安装

yarn add eslint -D

# 使用

# 初始化一个项目

项目下执行

  • 非全局 yarn eslint --init
  • 全局eslint --init
(1)How would you like to use ESLint?
    To check syntax only // 只检查语法性错误
    To check syntax and find problems // 检查语法错误并且发现问题代码
    > To check syntax, find problems, and enforce code style // 检查语法错误,发现问题代码,校验代码风格
    选第三个,检查语法错误,发现问题代码,校验代码风格
(2)What type of modules dos your project use?
    > JavaScript modules (import/export) // ESM:允许使用import/export
    CommonJS (require/exports) // CommonJS:允许使用require/exports
    None of these // 没有用到任何模块化
    选第一个,import/export
(3)Which framework does you project use?
    React
    > Vue.js
    None of these
    选vue
(4)Does your project use TypeScript? No / Yes  // 是否支持TypeScript
    输入yes
(5)Where does you code run? // 代码运行环境 多选 
    (*) Browser // 浏览器环境
    (*) Node // node环境
    两个都选
(6)How would you like to define a style for your project? // 你喜欢的代码风格
    > Use a popular style guide // 使用一个市面上的主流风格
    Answer questions about your style // 通过回答问题,形成一个风格
    Inspect your JavaScript file(s) // 根据JS代码文件,推断代码风格
    选第一个,市面主流风格
(7)Which style guide do you want to follow? // 选一个要使用的规范
    Airbnb: https://github.com/airbnb/javascript
    > Standard: https://github.com/standard/standard
    Google: https://github.com/google/eslint-config-google
    XO: https://github.com/xojs/eslint-config-xo
    选第二个,开源
(8)What format do you want your config file to be in?  // 配置文件类型
    > JavaScript
    YAML
    JSON
    选第一个JavaScript,js文件更利于扩展
(9)Would you like to install them now with npm? › No / Yes  // 现在用安装npm规范吗?
    选yes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

得到.eslintrc.js配置文件

module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  extends: [
    'plugin:vue/essential',
    'standard'
  ],
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module'
  },
  plugins: [
    'vue'
  ],
  rules: {
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 常用命令

示例

// 检测src目录下,.js,.jsx,.ts,.tsx类型,并自动进行修复
eslint src --ext .js,.jsx,.ts,.tsx --fix
1
2

官方文档 (opens new window)下面是一些命令选项的描述:

基本配置

  • --no-eslintrc:禁用 .eslintrc.* 和 package.json 文件中的配置。
  • -c, --config:该选项允许你为 ESLint指定一个额外的配置文件。
  • --env:用于指定环境。该选项只能启用环境,不能禁用在其它配置文件中设置的环境。要指定多个环境的话,使用逗号分隔它们,或多次使用这个选项。
  • --ext:可以指定在指定目录中搜索JavaScript文件时,ESLint将使用哪些文件扩展名。默认扩展名为.js。
  • --global:用于定义全局变量。任何指定的全局变量默认是只读的,在变量名字后加上 :true 后会使它变为可写。要指定多个变量,使用逗号分隔它们,或多次使用这个选项。

指定规则和插件

  • --rulesdir:该选项允许指定另一个加载规则文件的目录。
  • --plugin:用于指定一个要加载的插件。可以省略插件名的前缀 eslint-plugin-。
  • --rule:该选项指定要使用的规则。这些规则将会与配制文件中指定的规则合并。定义多个规则时使用逗号分隔它们,或多次使用这个选项。

解决问题选项

  • --fix:该选项指示 ESLint 试图修复尽可能多的问题。修复只针对实际文件本身,而且剩下的未修复的问题才会输出。
  • --fix-dry-run:该选项与 --fix 有相同的效果,唯一一点不同是,修复不会保存到文件系统中。
  • --fix-type:该选项允许你在使用 --fix 或 --fix-dry-run 时指定要应用的修复的类型。修复的三种类型是problem、suggestion、layout。

忽略文件选项

  • --ignore-path:该选项允许你指定一个文件作为 .eslintignore。默认情况下,ESLint 在当前工作目录下查找 .eslintignore。
  • --no-ignore:该选项禁止排除 .eslintignore、--ignore-path 和 --ignore-pattern 文件中指定的文件。
  • --ignore-pattern:该选项允许你指定要忽略的文件模式,除了 .eslintignore 中的模式之外。可以重复该选项以提供多个模式。

使用标准输入选项

  • --stdin:该选项告诉 ESLint 从 STDIN 而不是从文件中读取和检测源码。
  • --stdin-filename:该选项允许你指定一个文件名去处理 STDIN。当你处理从 STDIN 来的文件和有规则依赖于这个文件名时,这会很有用。

处理警告选项

  • --quiet:该选项允许你禁止报告警告。如果开启这个选项,ESLint 只会报告错误。
  • --max-warnings:该选项允许你指定一个警告的阈值,当你的项目中有太多违反规则的警告时,这个阈值被用来强制 ESLint 以错误状态退出。

其他

  • --init:该选项将会配置初始化向导。它被用来帮助新用户快速地创建 .eslintrc 文件,用户通过回答一些问题,选择一个流行的风格指南,或检查你的源文件,自动生成一个合适的配置。
  • --debug:该选项将调试信息输出到控制台。
  • -h, --help:该选项会输出帮助菜单,显示所有可用的选项。当有这个选项时,忽略其他所有选项。
  • -v, --version:该选项在控制台输出当前 ESlint 的版本。当有这个标记时,忽略其他所有标记。
  • --print-config:该选项输出传递的文件使用的配置。当有这个标记时,不进行检测,只有配置相关的选项才是有效的。

退出码
当检测文件时,ESLint 可以使用以下退出代码之一退出 :

  • 0:检测成功,没有错误。如果 --max-warnings 标志被设置为 n,那么警告数量最多为n。
  • 1:检测成功,并且至少有一个错误,或者警告多于 --max-warnings 选项所允许的警告。
  • 2:由于配置问题或内部错误,检测未能成功。

# 配置

# env

指定脚本的运行环境,每一个环境定义了一组预定义的全局变量,可以定义多个环境。

env: {
  browser: true,
  es2021: true,
  node: true
}
1
2
3
4
5

# parser

eslint解析器,默认[Espree],还有esprima (opens new window)、@babel/eslint-parser (opens new window)等解析器,没有过多的了解。官方参考 (opens new window)
typescript项目要使用@typescript-eslint/parser (opens new window)解析器
深入了解AST,可以点击这里 (opens new window)

# parserOptions

parser的解析配置,官方文档 (opens new window)

  • ecmaVersion 可以使用latest表示最新的 ECMA 版本

# vue需单独配置parser

  • eslint默认使用的parser解析器是@babel/eslint-parser,该parserjs、ts都能解析,但是@babel/eslint-parser中的规则不支持对ts进行lint,
  • 所以我们ts项目,要将解析器parser换成@typescript-eslint/parser,我们解析vue文件,要将parser换成vue-eslint-parser,
  • vue官方提供了vue-eslint-parser包来对.vue文件中template部分进行转换,script部分需要额外配置一个js/tsparser,可以在parserOption.parser中进行指定。
  • parserOptions配置的是解析js相关的配置,默认解析器parser为@babel/eslint-parser,vue使用ts的话,就要手动换成@typescript-eslint/parser
// .eslintrc.cjs
parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
  + parser: "@typescript-eslint/parser",
},
1
2
3
4
5
6

参考

  1. eslint parser配置实践 (opens new window)

# overrides

通常在一些项目中,我们需要针对不同的文件进行不同的 Lint 配置,那么此时 EsLint 同样为我们提供了 Overrides 选项来解决这个问题。
比如,我们项目中存在一些以 .test、.spec 结尾的测试文件,那么此时我们希望这些测试文件可以拥有不同的 Lint 配置规则。
那么我们就可以使用 Overrieds 配置来进行特定文件的规则覆盖,比如:

// .eslintrc.js
module.exports = {
  rules: {
      'no-console': 2
  },
  overrides: [
    // *.test.js 以及 *.spec.js 结尾的文件特殊定义某些规则
    {
      files: ['*-test.js', '*.spec.js'],
      rules: {
        'no-unused-expressions': 2,
      },
    },
  ],
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

上述的配置中,针对于 .test.js/.spce.js 的话既支持 no-console 的规则同时也开启了 no-unused-expressions 的规则。

# plugins

插件用来增强eslint能力。
如:eslint-plugin-prettier,把 prettier 的能力赋给 eslint,让 eslint 拥有和 prettier 一样的代码格式化能力。

缩写
plugin1等同于 eslint-plugin-plugin1

{
  plugins: [
    "prettier",  // 等同于  eslint-plugin-prettier
  ]
}
1
2
3
4
5

# extends

别人提前写好的一套rules,也就是一份别人配置好的.eslintrc.js

注意:

  • 数组中,后面的规则,会覆盖前面的

1.引入插件下的rules集

引入插件下的rules合集,必须以plugin开头,plugin:plugin_name/config_name

eslint-plugin-vue插件源码(位置:./node_modules/eslint-plugin-vue/lib/index.js)

module.exports = {
  rules: {
     // ...省略
  },
  configs: {
    base: require('./configs/base'),
    essential: require('./configs/essential'),
    'no-layout-rules': require('./configs/no-layout-rules'),
    recommended: require('./configs/recommended'),
    'strongly-recommended': require('./configs/strongly-recommended'),
    'vue3-essential': require('./configs/vue3-essential'),
    'vue3-recommended': require('./configs/vue3-recommended'),
    'vue3-strongly-recommended': require('./configs/vue3-strongly-recommended')
  },
  processors: {
    '.vue': require('./processor')
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

可以看到eslint-plugin-vue下configs提供了8套不同rulse规范,我们就可以引入任何一套作为项目检查vue文件的规范。

2. 引入别人写好的rules合集

全称eslint-config-myconfig,简称'myconfig

分析

module.exports = {
  extends: [
    'eslint:recommend',
    'plugin:vue/vue3-recommended',
    'prettier',
    'prettier/@typescript-eslint'
  ], 
  plugins: [],
  rules: {},
}
1
2
3
4
5
6
7
8
9
10
  • eslint:recommend 【插件】,没有eslint-config-eslint插件,说明是插件名/路径,在/node_modules/eslint/conf/eslint-recommended.js找到了,eslint内部封装的比较复杂,不知道怎么导出的recommend rules集合,只能说这个规则集合确实存在😂
  • plugin:vue/vue3-recommended 【插件】/node_modules/eslint-plugin-vue/lib/index.js下找到了configs.vue3-recommended
  • prettier 【config】/node_modules/eslint-config-prettier
  • prettier/@typescript-eslint 【config】/node_modules/eslint-config-prettier/@typescript-eslint.js

# rules

全部规则 (opens new window)

  • "off" 或 0 - 关闭规则
  • "warn" 或 1 - 开启规则,使用警告级别的错误:warn (不会导致程序退出)
  • "error" 或 2 - 开启规则,使用错误级别的错误:error (当被触发的时候,程序会退出)

1. 在某个文件里配置规则(只在当前文件中生效)

/* eslint eqeqeq: 0, curly: "error" */
1

2. 全局配置

{
    "plugins": [
        "plugin1",
        "react" // 配置 eslint-plugin-react 插件
    ],
    "rules": {
        "eqeqeq": "off",
        "curly": "error",
        "quotes": ["error", "double"],
        "plugin1/rule1": "error", // plugin1插件中的配置
        "react/jsx-boolean-value": 2 // 配置eslint-plugin-react 的 jsx-boolean-value 规则
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

规则 plugin1/rule1 表示来自插件 plugin1 的 rule1 规则

# globals

配置全局变量官方文档 (opens new window)

  • readonly/false——只读
  • writable/true——读写
  • off——禁用该全局变量

1. 当前文件定义(局部)

/* global $ */
console.log($) // 这样使用变量$ 就不会报错
1
2

2. 全局配置

// eslintrc.js内配置
module.exports = {
  extends: [
      // ...
  ],
  plugins: [
    //....
  ],
  // 在每个js文件都可以使用这些全局变量了
  "globals": {
    "$": true,
    "describe": true,
    "expect": true,
    "test": true,
  },
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 配置文件优先级

  • 如果项目目录下有多个配置文件,ESLint 只会使用一个,优先级为:.eslintrc.js > .eslintrc > package.json,一般我们都是在 .eslintrc.js 配置。
  • 同时,如果配置文件里没有"root": true这个属性,ESLint就会继续向外寻找配置文件,直到找到有"root": true的为止。
  • 建议给项目根目录的.eslintrc.js加上root: true

# 常用插件

1. eslint-plugin-html (opens new window)

通过这个插件你可以让eslint去检测html文件script标签里的js代码。使用示例:

// .eslintrc.js

{
    "plugins": [
        "html"
    ]
}
1
2
3
4
5
6
7

2. eslint-plugin-import

这个插件意在提供对ES6+ import/export语法的支持,有助于防止你写错文件路径或者引用的变量名。使用示例:

{
    "plugins": [
        "import"
    ],
    "rules": {
        "import/no-unresolved": [2, { "commonjs": true, "amd": true }],
        "import/named": 2,
        "import/namespace": 2,
        "import/default": 2,
        "import/export": 2,
        // # etc...
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

或者使用现成的推荐规则:

{
    "extends": {
        "eslint:recommended",
        "plugin:import/errors",
        "plugin:import/warnings"
    }
}
1
2
3
4
5
6
7

3. eslint-plugin-node

添加对node的eslint支持。使用示例:

{
    "plugins": ["node"],
    "extends": ["eslint:recommended", "plugin:node/recommended"],
    "rules": {
        "node/exports-style": ["error", "module.exports"],
    }
}
1
2
3
4
5
6
7

4. eslint-plugin-promise

{
    "plugins": [
        "promise"
    ],
    "rules": {
        "promise/always-return": "error",
        "promise/no-return-wrap": "error",
        "promise/param-names": "error",
        "promise/catch-or-return": "error",
        "promise/no-native": "off",
        "promise/no-nesting": "warn",
        "promise/no-promise-in-callback": "warn",
        "promise/no-callback-in-promise": "warn",
        "promise/avoid-new": "warn",
        "promise/no-return-in-finally": "warn"
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

或者直接使用现成的推荐规则:

{
    "extends": [
        "plugin:promise/recommended"
    ]
}
1
2
3
4
5

5. eslint-plugin-standard

这是一个为Standard Linter而做的补充插件,一共就扩展了4个规则,使用示例如下:

{
  rules: {
    'standard/object-curly-even-spacing': [2, "either"]
    'standard/array-bracket-even-spacing': [2, "either"],
    'standard/computed-property-even-spacing': [2, "even"]
    'standard/no-callback-literal': [2, ["cb", "callback"]]
  }
}
1
2
3
4
5
6
7
8

6. eslint-plugin-n

未知

7. eslint-plugin-vue

添加对Vue的支持

# 相关链接

eslint中文网 (opens new window)

编辑 (opens new window)
#eslint
上次更新: 2022/09/04
npm
prettier

← npm prettier→

最近更新
01
mock使用
07-12
02
websocket即时通讯
07-12
03
前端面试题
07-09
更多文章>
Theme by Vdoing | Copyright © 2022-2023 NeverStop1024 | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式