簡介
- 檢查語法錯誤
- 檢查語法風格
- 修正語法
安裝
//項目內安裝
npm i -D eslint
//全局安裝
npm i -g eslint
初始化配置
eslint --init
運行該命令將會在目錄下生成一個.eslintrc(.js|.json|.yml)文件,該文件就是eslint規則的配置文件
實例
{
"rules": {
"semi": ["error", "always"],
"quotes": ["error", "double"]
}
}
"semi"和"quotes"就是ESLint中的配置規則名,[“error”, “always”]和[“error”, “double”]就是對應的配置,“error"參數代表該規則的錯誤等級,該等級有"off”,“warn”,"error"三種。"always"和"double"則是具體的配置項。
配置
環境
{
"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全局變量。
配置插件
{
"plugins": [
"plugin1",
"eslint-plugin-plugin2"
]
}
讓一組文件不接受規則校驗
{
"rules": {...},
"overrides": [
{
"files": ["*-test.js","*.spec.js"],
"rules": {
"no-unused-expressions": "off"
}
}
]
}
忽略一些文件
需要添加.eslintignore,內容格式如下:
**/*.js
**/*.js
**/*.js
**/*.js
配置擴展文件
{
"rules":{...},
"extends":"airbnb-base"
}
rules中的規則會覆蓋擴展中的規則
命令行
在全局安裝的情況下,可以使用eslint命令行
校驗文件
eslint file.js
指定配置文件
eslint -c myconfig file.js
修復語法
eslint --fix file.js
將錯誤報告輸出
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
有色輸出
eslint --color file.js
添加緩存
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