ESLint 是一个代码检查工具,它能按照定义的规则来检查代码是否符合规范。对于需要编译的静态语言来说,编译器在编译的时候可以自动检查代码规范。但是对于解释执行的动态语言来说,只能在运行的时候调试,而且一些运行在浏览器之外的 JS 也 不太方便调试。

ESLint 可以让程序员在编码的过程中就发现问题,而不是在程序执行中。ESLint 也可以配合 Webpack 之类的构建工具一起使用,ESLint 还能通过插件集成在一些编辑器中。

这里写的主要是 ESLint 的简单配置和使用,关于配合 Webpack 和 编辑器使用后面还会写。

安装

npm 全局安装:

npm -g eslint

npm 本地安装:

npm install --save-dev eslint

本地安装之前需要输入:

npm init

创建 package.json 来初始化项目。

下面我演示的时候会使用本地安装。

ESLint 初始化

本地安装的 ESLint 可以输入:

npx eslint --init

初始化 ESLint 的配置。

如果是全局安装的 ESLint 可以直接输入:

eslint --init

初始化配置,主要就是去除 npx

首先是选择 ESLint 的使用方式,如下:

 How would you like to use ESLint? (Use arrow keys)     
  To check syntax only
> To check syntax and find problems
  To check syntax, find problems, and enforce code style 

使用上下光标键选择,回车确定。

然后选择模块类型:

What type of modules does your project use? (Use arrow keys)       
> JavaScript modules (import/export)
  CommonJS (require/exports)
  None of these

然后选择你使用的框架:

 Which framework does your project use? 
  React
  Vue.js
> None of these

是否使用 TypeScript:

Does your project use TypeScript? (y/N)

可以输入 yn

运行环境:

Where does your code run? (Press <space> to select, <a> to toggle all, <i> to invert selection)
>(*) Browser
 ( ) Node

浏览器和 Node 可以同时选择,按空格键选择,回车确定。

选择 ESLint 配置文件的类型:

What format do you want your config file to be in? 
  JavaScript
  YAML
> JSON

我选择的是 json,在初始化完成后会在项目根目录生成一个 .eslintrc.json 的配置文件。

简单使用

src/index.js 中有如下内容:

var a = 1;
var b = '123';

这样的代码一般在运行的时候是不会报错的,下面使用 ESLint 检查一下。

检查 src/index.js

npx eslint src/index.js

检查结果如下:

 1:5  error  'a' is assigned a value but never used  no-unused-vars
  2:5  error  'b' is assigned a value but never used  no-unused-vars

✖ 2 problems (2 errors, 0 warnings)
上面变量中分配的值都没有使用过。

修改一下 src/index.js

var a = 1;
var b = '123';
console.log(a);
console.log(b);

这次没有输出任何内容,说明没问题。

配置文件简单说明

上面初始化的配置文件内容如下:

{
  "env": {
    "browser": true,
    "es6": true,
    "node": true
  },
  "extends": "eslint:recommended",
  "globals": {
    "Atomics": "readonly",
    "SharedArrayBuffer": "readonly"
  },
  "parserOptions": {
    "ecmaVersion": 2018,
    "sourceType": "module"
  },
  "rules": {}
}

env (Environments)

运行环境,里面包含一些预定义的全局变量。这里定义了 browser es6node

如需查看所有支持的变量可以访问 https://cn.eslint.org/docs/user-guide/configuring#specifying-environments

extends

配置文件的位置,ESLint 可支持多个配置文件。

globals

额外的全局变量。

parserOptions

要支持的 JS 语法。下面是配置说明:

  • ecmaVersion:ECMAScript 版本,可以使用数字版本号,也可以使用年份版本号。
  • sourceType: 可以设置为 scriptmodule
  • ecmaFeatures: 额外的语言特性,它的值是一个对象,globalReturn:允许在全局作用域下使用 returnimpliedStrict:启用全局 strict mode (如果 ecmaVersion 是 5 或更高),jsx:启用 JSX。

rules

定义 ESLint 的规则。

下面定义一个规则,如果代码中出现 console 就提示错误:

{
  "rules": {
    "no-console": "error"
  }
}

要检查的 JS 代码如下:

var a = 1;
var b = '123';
console.log(a);
console.log(b);

检查结果如下:

3:1  error  Unexpected console statement  no-console
  4:1  error  Unexpected console statement  no-console

✖ 2 problems (2 errors, 0 warnings)

如果你在 Vue-Cli 创建的项目中使用 console 调试时报错很可能就是因为开启了 no-console

规则支持的值如下:

  • off0 关闭规则。
  • warn1 开启规则,使用警告级别的提示。
  • error2 开启规则,使用错误级别的提示。

如需查看完整的规则说明可以访问 https://cn.eslint.org/docs/rules/

plugins

插件配置,在配置之前需要先安装插件。

代码风格检查

ESLint 除了能检查代码错误外还能约束代码风格,对于多人开发来说,统一代码风格可以使代码更利于阅读和管理。

ESLint 初始化的时候,How would you like to use ESLint? 这一步可以选择 To check syntax, find problems, and enforce code style ,如下:

 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 

ESLint 也包含一些代码风格的预设,在 How would you like to define a style for your project? 这一步可以选择使用流行的预设风格或自定义,如下:

 How would you like to define a style for your project? (Use arrow keys)
> Use a popular style guide
  Answer questions about your style
  Inspect your JavaScript file(s)

初始化向导中包含三种预设风格,分别是 Airbnb、标准、Google ,如下:

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 

如果选择了使用预设,在初始化完成后 ESLint 会自动安装所需的相关插件。

使用了预设的代码风格,代码的格式就需要按照预设的标准来写,下面是一段简单的 JS 代码:

const a=1;

if(a==1){
    console.log(a);
}

使用 ESLint 检查一下:

1:11  error  Expected linebreaks to be 'LF' but found 'CRLF'  linebreak-style
  2:1   error  Expected linebreaks to be 'LF' but found 'CRLF'  linebreak-style
  3:1   error  Expected space(s) after "if"                     keyword-spacing
  3:9   error  Missing space before opening brace               space-before-blocks
  3:10  error  Expected linebreaks to be 'LF' but found 'CRLF'  linebreak-style
  4:1   error  Expected indentation of 2 spaces but found 4     indent
  4:20  error  Expected linebreaks to be 'LF' but found 'CRLF'  linebreak-style
  5:2   error  Newline required at end of file but not found    eol-last

✖ 8 problems (8 errors, 0 warnings)
  8 errors and 0 warnings potentially fixable with the `--fix` option.

代码风格的问题可以使用 --fix 选项修正,比如我要修复 src/index.js 命令如下:

npx eslint src/index.js --fix

修正后的代码如下:

const a = 1;

if (a == 1) {
  console.log(a);
}

以上就是 ESLint 的简单配置和使用,后面还会写搭配 Webpack 使用和编辑器配置。

相关文章: