简介

  • 检查语法错误
  • 检查语法风格
  • 修正语法

安装

1
2
3
4
5
//项目内安装
npm i -D eslint

//全局安装
npm i -g eslint

初始化配置

1
eslint --init

运行该命令将会在目录下生成一个.eslintrc(.js|.json|.yml)文件,该文件就是eslint规则的配置文件

实例

1
2
3
4
5
6
{
"rules": {
"semi": ["error", "always"],
"quotes": ["error", "double"]
}
}

“semi”和”quotes”就是ESLint中的配置规则名,[“error”, “always”]和[“error”, “double”]就是对应的配置,”error”参数代表该规则的错误等级,该等级有”off”,”warn”,”error”三种。”always”和”double”则是具体的配置项。

配置

环境

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

可配置的环境还有:

  • browser - 浏览器全局变量。
  • node - Node.js全局变量和Node.js范围。
  • commonjs - CommonJS全局变量和CommonJS范围(将此用于使用Browserify / WebPack的仅浏览器代码)。
  • shared-node-browser - Node.js和Browser共有的全局变量。
  • es6- 启用除模块之外的所有ECMAScript 6功能(这会自动将ecmaVersion解析器选项设置为6)。
  • worker - worker全局变量。
  • amd- 根据amd规范定义require()和define()作为全局变量。
  • mocha - 添加所有Mocha测试全局变量。
  • jasmine - 为版本1.3和2.0添加了所有Jasmine测试全局变量。
  • 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 - serviceworker全局变量。
  • atomtest - atom test辅助全局变量。
  • embertest - Ember测试辅助全局变量。
  • webextensions - WebExtensions全局变量。
  • greasemonkey - GreaseMonkey全局变量。

配置插件

1
2
3
4
5
6
{
"plugins": [
"plugin1",
"eslint-plugin-plugin2"
]
}

让一组文件不接受规则校验

1
2
3
4
5
6
7
8
9
10
11
{
"rules": {...},
"overrides": [
{
"files": ["*-test.js","*.spec.js"],
"rules": {
"no-unused-expressions": "off"
}
}
]
}

忽略一些文件

需要添加.eslintignore,内容格式如下:

1
2
3
4
**/*.js
**/*.js
**/*.js
**/*.js

配置扩展文件

1
2
3
4
{
"rules":{...},
"extends":"airbnb-base"
}

rules中的规则会覆盖扩展中的规则

命令行

在全局安装的情况下,可以使用eslint命令行

校验文件

1
eslint file.js

指定配置文件

1
eslint -c myconfig file.js

修复语法

1
eslint --fix file.js

将错误报告输出

1
eslint -f html file.js -o out.html

-o: 输出文件名
-f: 输出文件格式

可接受格式有:

  • checkstyle
  • codeframe
  • compact
  • html
  • jslint-xml
  • json
  • junit
  • stylish (the default)
  • table
  • tap
  • unix
  • visualstudio

有色输出

1
eslint --color file.js

添加缓存

1
eslint --cache file.js

会记录已经校验过的文件,优化eslint性能

规则

见官网:https://eslint.org/docs/rules/

扩展推荐

  • eslint-config-airbnb-base
  • eslint-config-standard
  • eslint-config-alloy
  • eslint-config-google
  • eslint-config-prettier