安装
全局安装
npm i -g eslint
本地安装(推荐)
npm i -D eslint
2022 年 4 月份,如果想选择 eslint-config-standard 这套代码规范,则需要安装 eslint@7,不要安装 eslint@8。
npm i -D eslint@7
创建配置文件
运行 eslint --init 之后,回答一些问题, 自动创建 .eslintrc 配置文件。
# 全局
eslint --init
# 本地
npx eslint --init
执行 eslint --init 命令之后,系统会问你问题,第一个问题推荐选择第三个选项。
? 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
下面的问题推荐第一个选项,选择 extends 一个流行的共享配置包,也就是选择一套流行的代码规范。
? 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)
我自己选择的是 eslint-config-standard 这套代码规范,你也可以选择其余的几个。
? 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
选择 eslint-config-standard 之后,会提示你是否下载对应的 npm 包,选择是就会自动下载需要的 npm 包。
2022 年 4 月份,如果想选择 eslint-config-standard 这套代码规范,则需要安装 eslint@7,不要安装 eslint@8。
检测命令
eslint 命令后面可以跟着文件、目录、glob 模式,以下所有命令都以全局安装的 ESLint 的形式展示,本地安装的 ESLint 命令需要执行 npx eslint。
eslint [options] [file|dir|glob]*
指定文件名检测
eslint file1.js file2.js
指定目录,会检测该目录以及子目录下的所有 .js 文件
eslint src
指定 glob 模式,检测匹配该模式的所有文件(glob 模式有点类似正则表达式,专门用于匹配文件使用的)。
eslint lib/**
常用参数
--no-eslintrc
禁用所有 .eslintrc.* 配置文件。
eslint --no-eslintrc app.js
--config
通过 -c 或者 --config 可以指定一个额外的配置文件,该配置文件拥有最高优先级,会覆盖各个层级的 .eslintrc.* 的配置文件的配置信息。注意这种方式仍然会通过层级叠加的方式使用到各个目录中的 .eslintrc.* 配置文件,只不过指定的文件的配置信息拥有最高的优先级。
eslint -c ~/my-eslint.json app.js
eslint --config ~/my-eslint.json app.js
通过结合 --no-eslintrc 和 --config 可以只使用指定的文件作为唯一的配置文件。
eslint --no-eslintrc --config ~/my-eslint.json app.js
--ext
指定检测的文件扩展名,默认为 .js 文件,只有在检测目录的时候才会用到 --ext 的参数,如果检测一个具体的文件,则会忽略 --ext 的参数。
eslint --ext .js --ext .ts src
或者
eslint --ext .js,.ts src
--fix
当检测出问题之后会尝试修复有问题的代码,使用该参数会修改你的源代码。
eslint --fix src
其他
--parser --parser-options --env --global --plugin --rule 这些参数指定的配置信息,可以完全在配置文件来指定,不推荐在命令行使用这些参数。











网友评论