ESLint使用

1 lint 简介

lint 最早用于 c 语言,用来检查代码。目前作为通用术语,用来表示代码检查工具。

JS 经历的主流 lint 工具如下:

1、JSLint

2、JSHint

3、Eslint

2 ESlint 配置

2.1 初始化项目

1
2
//在新建好的文件夹下,执行如下命令,得到 package.json
npm init -y

2.2 安装&初始化 ESLint

1
2
3
4
5
6
7
8
9
10
11
//方式一:全局安装 & 初始化  
npm install eslint -g //安装
eslint --init //初始化


//方式二:本地安装 & 初始化 ====》推荐方式
//安装
npm insall eslint
//初始化
.\node_modules\.bin\eslint --init //window平台
./node_modules/.bin/eslint --init //linux平台

根据项目实际情况选择,完成后可得到规则配置文件 .eslintrc.js 或 .eslintrc.ymal 或 eslintrc.json,下面是对 .eslintrc.js 文件的内容解析:

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
module.exports = {
//通过定义 env 来预定义对应的全局变量
//可选 env 的配置值如下:
/*
browser - 浏览器环境中的全局变量。
node - Node.js 全局变量和 Node.js 作用域。
commonjs - CommonJS 全局变量和 CommonJS 作用域 (用于 Browserify/WebPack 打包的只在浏览器中运行的代码)。
shared-node-browser - Node.js 和 Browser 通用全局变量。
es6 - 启用除了 modules 以外的所有 ECMAScript 6 特性(该选项会自动设置 ecmaVersion 解析器选项为 6)。
worker - Web Workers 全局变量。
amd - 将 require() 和 define() 定义为像 amd 一样的全局变量。
mocha - 添加所有的 Mocha 测试全局变量。
jasmine - 添加所有的 Jasmine 版本 1.3 和 2.0 的测试全局变量。
jest - Jest 全局变量。
phantomjs - PhantomJS 全局变量。
protractor - Protractor 全局变量。
qunit - QUnit 全局变量。
jquery - jQuery 全局变量。
prototypejs - Prototype.js 全局变量。
shelljs - ShellJS 全局变量。
meteor - Meteor 全局变量。
mongo - MongoDB 全局变量。
applescript - AppleScript 全局变量。
nashorn - Java 8 Nashorn 全局变量。
serviceworker - Service Worker 全局变量。
atomtest - Atom 测试全局变量。
embertest - Ember 测试全局变量。
webextensions - WebExtensions 全局变量。
greasemonkey - GreaseMonkey 全局变量。
*/
"env": {
"browser": true,
"es6": true,
"node": true
},

//extend 属性值
//eslint:all 表示启用当前安装的 ESLint 中所有的核心规则,慎用,因为会随 eslint 的版本变动而更新
//可以配置文件的绝对/相对路径,相对路径相对于当前配置文件(除非当前配置在home路径或非 eslint 安装目录的父级目录)。
// "./node_modules/coding-standard/.eslintrc-es6"
"extends": [
//eslint:recommended 表示所有在 https://eslint.bootcss.com/docs/rules/ 被标记为对号的规则将会默认开启
"eslint:recommended",
"plugin:react/recommended"
"airbnb"
],

//使用 globals 选项配置全局变量
//注意:要启用 no-global-assign 规则来禁止对只读的全局变量进行修改
"globals": {
"Atomics": false, //false表示该变量只读
"SharedArrayBuffer": false
},
//默认值 esprima,不解析非 es5 语法
"parser": "babel-eslint",//让 eslint 支持 babel 语法

//默认情况下,ESLint 支持 ECMAScript 5 语法
//配置parserOptions来 启用对 ECMAScript 其它版本和 JSX 的支持
"parserOptions": {
"ecmaFeatures": {//ecmaFeatures配置想额外使用的语言特性
//对JSX 语法的支持不用于对 React 的支持,想要支持React,推荐使用 eslint-plugin-reac
"jsx": true
},

//ecmaVersion来配置ecma对应版本语法的支持;
//要额外支持新的 ES6 全局变量,使用 { "env":{ "es6": true } };
"ecmaVersion": 2018,

//sourceType默认值为"script"
"sourceType": "module"
},

//parser选项配置解析器 默认值为esprima,可选值还有eslint-babel, @typescript-eslint/parser
"parser": "eslint-babel",

//plugins 选项配置第三方插件,插件安装后才能使用
//全局安装的 eslint 只能使用全局安装的插件
"plugins": [
"react"
],

//使用rules选项配置项目要使用的规则
/*
"off" or 0 - 关闭规则
"warn" or 1 - 开启规则 提示信息为告警级别
"error" or 2 - 开启规则 提示信息为报错级别
*/
"rules": {
quotes: ["error", "double"],//当规则有其他选项时,可使用数组来指定规则的值
"plugin1/rule1": "error" //使用插件中的规则时,需要使用 插件名/规则ID 的形式
}
};

2.3 配置ESLint规则

2.3.1 配置方式

主要有两种方式类配置ESLint:

  • 注释
  • 配置文件

注释

通过在源码文件中添加注释来配置lint规则,此方法通常用于临时临时禁止某些严格的lint警告

1
2
//放在文件顶部整个文件都不会有警告了
/* eslint-disable */

配置文件

配置文件类型

文件类型及优先级排序如下:

  1. .eslintrc.js
  2. .eslintrc.yaml
  3. .eslintrc.yml
  4. .eslintrc.json
  5. .eslintrc(弃用)
  6. package.json //在 package.json 里创建eslintConfig属性,在此属性中进行配置
配置文件使用方式

配置文件有两种使用方式,无论哪种方式配置文件都会覆盖默认设置。

  • .eslintrc.* 和 package.json

    ​ 使用 .eslintrc.*package.json 文件,eslint 将自动从被检测目录开始寻找(可通过配置root:true来阻止 eslint),直到系统根目录,当想对项目的不同部分分别进行配置时,这种方式很有用。

    此方式需要注意:

    • .eslintrc.* 文件可以进行层叠配置。

      eslint 会将被检测文件目录层次结构中的 eslint 配置文件规则进行组合,离被检测文件最近的规则优先级最高。如检测下面代码结构中的 test.js 文件时,your-project/tests/.eslintrc文件优先级要高于your-project/.eslintrc 文件。

      1
      2
      3
      4
      5
      6
      7
      your-project
      ├── .eslintrc
      ├── lib
      │ └── source.js
      └─┬ tests
      ├── .eslintrc
      └── test.js
    • 同一目录下 .eslintrcpackage.json 同时存在时,.eslintrc 优先级高会被使用,package.json 文件将不会被使用。
  • 命令行参数 -c

    使用 -c 参数,来传递配置文件。想要 eslint 忽略任何 .eslintrc.* 文件,需使用 --no-eslintrc 的同时,加上 -c 标记。

    1
    eslint -c myconfig.json myfiletotest.js
配置规则优先级总结
  • 优先级从高到底:

    • 行内配置
      1. /*eslint-disable*//*eslint-enable*/
      2. ``/global/`
      3. /*eslint*/
      4. ``/eslint-env/`
    • 命令行选项(或 CLIEngine 等价物):
      1. --global
      2. ``–rule`
      3. --env
      4. -c--config
    • 项目级配置:
      1. 与要检测的文件在同一目录下的 .eslintrc.*package.json 文件
      2. 继续在父级目录寻找 .eslintrcpackage.json 文件,直到根目录(包括根目录)或直到发现一个包含 "root": true 的配置文件。
    • 如果不是上面类型中的任何一种情况,则退回到 ~/.eslintrc 中自定义的默认配置。
  • 具体规则说明:

    https://eslint.bootcss.com/docs/rules/

2.4 配置忽略文件

  • .eslintignore
  • –ignore-path
  • package.json
.eslintignore

在项目根目录,创建.eslintignore文件,在文件中指定需要忽略的文件和目录。每一行都是一个 glob 模式表明哪些路径应该忽略检测。

Globs 匹配使用 node-ignore,所以大量可用的特性有:

  • 注释以 # 开头
  • 路径是相对于 .eslintignore 的位置或当前工作目录。这也会影响通过 --ignore-pattern传递的路径。
  • 忽略模式同 .gitignore 规范
  • ! 开头的行是否定模式,它将会重新包含一个之前被忽略的模式。

除了 .eslintignore 文件中的模式,eslint总是忽略 /node_modules/*/bower_components/* 中的文件。

–ignore-path

在命令行使用 --ignore-path 选项指定忽略项所在配置文件。指定 --ignore-path 意味着任何现有的 .eslintignore 文件将不被使用。

1
eslint --ignore-path .jshintignore file.js
package.json

如果没有发现 .eslintignore 文件,也没有指定替代文件,ESLint 将在 package.json 文件中查找 eslintIgnore 键。

1
2
3
4
5
6
7
8
9
10
11
{
"name": "mypackage",
"version": "0.0.1",
"eslintConfig": {
"env": {
"browser": true,
"node": true
}
},
"eslintIgnore": ["hello.js", "world.js"]
}

2.5 命令行说明

命令行选项可以通过.\node_modules\.bin\eslint -h 查看,得到如下信息:

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
eslint [options] file.js [file.js] [dir]

Basic configuration:
//禁用 .eslintrc.* 和 package.json 文件中的配置
--no-eslintrc Disable use of configuration from .eslintrc.*
//指定一个其他的配置文件
-c, --config path::String Use this configuration, overriding .eslintrc.* config options if present
//--ext 只有在参数为目录时,才生效
--env [String] Specify environments
--ext [String] Specify JavaScript file extensions - default: .js
--global [String] Define global variables
--parser String Specify the parser to be used
--parser-options Object Specify parser options
--resolve-plugins-relative-to path::String A folder where plugins should be resolved from, CWD by default

Specifying rules and plugins:
--rulesdir [path::String] Use additional rules from this directory
--plugin [String] Specify plugins
--rule Object Specify rules

Fixing problems:
--fix Automatically fix problems
--fix-dry-run Automatically fix problems without saving the changes to the file system
--fix-type Array Specify the types of fixes to apply (problem, suggestion, layout)

Ignoring files:
--ignore-path path::String Specify path of ignore file
--no-ignore Disable use of ignore files and patterns
--ignore-pattern [String] Pattern of files to ignore (in addition to those in .eslintignore)

Using stdin:
--stdin Lint code provided on <STDIN> - default: false
--stdin-filename String Specify filename to process STDIN as

Handling warnings:
--quiet Report errors only - default: false
--max-warnings Int Number of warnings to trigger nonzero exit code - default: -1

Output:
-o, --output-file path::String Specify file to write report to
-f, --format String Use a specific output format - default: stylish
--color, --no-color Force enabling/disabling of color

Inline configuration comments:
--no-inline-config Prevent comments from changing config or rules
--report-unused-disable-directives Adds reported errors for unused eslint-disable directives

Caching:
--cache Only check changed files - default: false
--cache-file path::String Path to the cache file. Deprecated: use --cache-location - default: .eslintcache
--cache-location path::String Path to the cache file or directory

Miscellaneous:
--init Run config initialization wizard - default: false
--env-info Output execution environment information - default: false
--debug Output debugging information
-h, --help Show help
-v, --version Output the version number
--print-config path::String Print the configuration for the given file

参考链接:

https://eslint.bootcss.com/docs/

https://eslint.org/docs/user-guide/configuring