安裝
環(huán)境需求:Node.js(>=4.x), npm version 2+.
//全局
npm install eslint -g
//局部
npm install eslint --save-dev
使用
//局部
//命令行中
./node_modules/.bin/eslint --init
//在腳本中
requeire('eslint')(options)
配置
目錄:
名字:.eslintrc.*(比如:.eslintrc.json摧冀、.eslintrc)
內(nèi)容:
環(huán)境-which environments your script is designed to run in
變量- the additional global variables your script accesses during execution
規(guī)則-which rules are enabled and at what error level.
解析-allows you to specify the JavaScript language options you want to support.
ES6-語(yǔ)法轉(zhuǎn)換: { "parserOptions": { "ecmaVersion": 6 } }
ES6-接口轉(zhuǎn)換:{ "env": { "es6": true } }
其解析器:"parser": "esprima",
.eslintrc
{
"rules": {
"semi": ["error", "always"],
"quotes": ["error", "double"]
}
}
規(guī)則
"no-alert": 0,//禁止使用alert confirm prompt
"no-array-constructor": 2,//禁止使用數(shù)組構(gòu)造器
"no-bitwise": 0,//禁止使用按位運(yùn)算符
"no-caller": 1,//禁止使用arguments.caller或arguments.callee
"no-catch-shadow": 2,//禁止catch子句參數(shù)與外部作用域變量同名
"no-class-assign": 2,//禁止給類賦值
"no-cond-assign": 2,//禁止在條件表達(dá)式中使用賦值語(yǔ)句
"no-console": 2,//禁止使用console
"no-const-assign": 2,//禁止修改const聲明的變量
"no-constant-condition": 2,//禁止在條件中使用常量表達(dá)式 if(true) if(1)
"no-continue": 0,//禁止使用continue
"no-control-regex": 2,//禁止在正則表達(dá)式中使用控制字符
"no-debugger": 2,//禁止使用debugger
"no-delete-var": 2,//不能對(duì)var聲明的變量使用delete操作符
"no-div-regex": 1,//不能使用看起來(lái)像除法的正則表達(dá)式/=foo/
"no-dupe-keys": 2,//在創(chuàng)建對(duì)象字面量時(shí)不允許鍵重復(fù) {a:1,a:1}
"no-dupe-args": 2,//函數(shù)參數(shù)不能重復(fù)
"no-duplicate-case": 2,//switch中的case標(biāo)簽不能重復(fù)
"no-else-return": 2,//如果if語(yǔ)句里面有return,后面不能跟else語(yǔ)句
"no-empty": 2,//塊語(yǔ)句中的內(nèi)容不能為空
"no-empty-character-class": 2,//正則表達(dá)式中的[]內(nèi)容不能為空
"no-empty-label": 2,//禁止使用空l(shuí)abel
"no-eq-null": 2,//禁止對(duì)null使用==或!=運(yùn)算符
"no-eval": 1,//禁止使用eval
"no-ex-assign": 2,//禁止給catch語(yǔ)句中的異常參數(shù)賦值
"no-extend-native": 2,//禁止擴(kuò)展native對(duì)象
"no-extra-bind": 2,//禁止不必要的函數(shù)綁定
"no-extra-boolean-cast": 2,//禁止不必要的bool轉(zhuǎn)換
"no-extra-parens": 2,//禁止非必要的括號(hào)
"no-extra-semi": 2,//禁止多余的冒號(hào)
"no-fallthrough": 1,//禁止switch穿透
"no-floating-decimal": 2,//禁止省略浮點(diǎn)數(shù)中的0 .5 3.
"no-func-assign": 2,//禁止重復(fù)的函數(shù)聲明
"no-implicit-coercion": 1,//禁止隱式轉(zhuǎn)換
"no-implied-eval": 2,//禁止使用隱式eval
"no-inline-comments": 0,//禁止行內(nèi)備注
"no-inner-declarations": [2, "functions"],//禁止在塊語(yǔ)句中使用聲明(變量或函數(shù))
"no-invalid-regexp": 2,//禁止無(wú)效的正則表達(dá)式
"no-invalid-this": 2,//禁止無(wú)效的this,只能用在構(gòu)造器蔼卡,類,對(duì)象字面量
"no-irregular-whitespace": 2,//不能有不規(guī)則的空格
"no-iterator": 2,//禁止使用__iterator__ 屬性
"no-label-var": 2,//label名不能與var聲明的變量名相同
"no-labels": 2,//禁止標(biāo)簽聲明
"no-lone-blocks": 2,//禁止不必要的嵌套塊
"no-lonely-if": 2,//禁止else語(yǔ)句內(nèi)只有if語(yǔ)句
"no-loop-func": 1,//禁止在循環(huán)中使用函數(shù)(如果沒有引用外部變量不形成閉包就可以)
"no-mixed-requires": [0, false],//聲明時(shí)不能混用聲明類型
"no-mixed-spaces-and-tabs": [2, false],//禁止混用tab和空格
"linebreak-style": [0, "windows"],//換行風(fēng)格
"no-multi-spaces": 1,//不能用多余的空格
"no-multi-str": 2,//字符串不能用\換行
"no-multiple-empty-lines": [1, {"max": 2}],//空行最多不能超過(guò)2行
"no-native-reassign": 2,//不能重寫native對(duì)象
"no-negated-in-lhs": 2,//in 操作符的左邊不能有!
"no-nested-ternary": 0,//禁止使用嵌套的三目運(yùn)算
"no-new": 1,//禁止在使用new構(gòu)造一個(gè)實(shí)例后不賦值
"no-new-func": 1,//禁止使用new Function
"no-new-object": 2,//禁止使用new Object()
"no-new-require": 2,//禁止使用new require
"no-new-wrappers": 2,//禁止使用new創(chuàng)建包裝實(shí)例加酵,new String new Boolean new Number
"no-obj-calls": 2,//不能調(diào)用內(nèi)置的全局對(duì)象磕道,比如Math() JSON()
"no-octal": 2,//禁止使用八進(jìn)制數(shù)字
"no-octal-escape": 2,//禁止使用八進(jìn)制轉(zhuǎn)義序列
"no-param-reassign": 2,//禁止給參數(shù)重新賦值
"no-path-concat": 0,//node中不能使用__dirname或__filename做路徑拼接
"no-plusplus": 0,//禁止使用++,--
"no-process-env": 0,//禁止使用process.env
"no-process-exit": 0,//禁止使用process.exit()
"no-proto": 2,//禁止使用__proto__屬性
"no-redeclare": 2,//禁止重復(fù)聲明變量
"no-regex-spaces": 2,//禁止在正則表達(dá)式字面量中使用多個(gè)空格 /foo bar/
"no-restricted-modules": 0,//如果禁用了指定模塊昧廷,使用就會(huì)報(bào)錯(cuò)
"no-return-assign": 1,//return 語(yǔ)句中不能有賦值表達(dá)式
"no-script-url": 0,//禁止使用javascript:void(0)
"no-self-compare": 2,//不能比較自身
"no-sequences": 0,//禁止使用逗號(hào)運(yùn)算符
"no-shadow": 2,//外部作用域中的變量不能與它所包含的作用域中的變量或參數(shù)同名
"no-shadow-restricted-names": 2,//嚴(yán)格模式中規(guī)定的限制標(biāo)識(shí)符不能作為聲明時(shí)的變量名使用
"no-spaced-func": 2,//函數(shù)調(diào)用時(shí) 函數(shù)名與()之間不能有空格
"no-sparse-arrays": 2,//禁止稀疏數(shù)組粘拾, [1,,2]
"no-sync": 0,//nodejs 禁止同步方法
"no-ternary": 0,//禁止使用三目運(yùn)算符
"no-trailing-spaces": 1,//一行結(jié)束后面不要有空格
"no-this-before-super": 0,//在調(diào)用super()之前不能使用this或super
"no-throw-literal": 2,//禁止拋出字面量錯(cuò)誤 throw "error";
"no-undef": 1,//不能有未定義的變量
"no-undef-init": 2,//變量初始化時(shí)不能直接給它賦值為undefined
"no-undefined": 2,//不能使用undefined
"no-unexpected-multiline": 2,//避免多行表達(dá)式
"no-underscore-dangle": 1,//標(biāo)識(shí)符不能以_開頭或結(jié)尾
"no-unneeded-ternary": 2,//禁止不必要的嵌套 var isYes = answer === 1 ? true : false;
"no-unreachable": 2,//不能有無(wú)法執(zhí)行的代碼
"no-unused-expressions": 2,//禁止無(wú)用的表達(dá)式
"no-unused-vars": [2, {"vars": "all", "args": "after-used"}],//不能有聲明后未被使用的變量或參數(shù)
"no-use-before-define": 2,//未定義前不能使用
"no-useless-call": 2,//禁止不必要的call和apply
"no-void": 2,//禁用void操作符
"no-var": 0,//禁用var窄锅,用let和const代替
"no-warning-comments": [1, { "terms": ["todo", "fixme", "xxx"], "location": "start" }],//不能有警告?zhèn)渥?"no-with": 2,//禁用with
"array-bracket-spacing": [2, "never"],//是否允許非空數(shù)組里面有多余的空格
"arrow-parens": 0,//箭頭函數(shù)用小括號(hào)括起來(lái)
"arrow-spacing": 0,//=>的前/后括號(hào)
"accessor-pairs": 0,//在對(duì)象中使用getter/setter
"block-scoped-var": 0,//塊語(yǔ)句中使用var
"brace-style": [1, "1tbs"],//大括號(hào)風(fēng)格
"callback-return": 1,//避免多次調(diào)用回調(diào)什么的
"camelcase": 2,//強(qiáng)制駝峰法命名
"comma-dangle": [2, "never"],//對(duì)象字面量項(xiàng)尾不能有逗號(hào)
"comma-spacing": 0,//逗號(hào)前后的空格
"comma-style": [2, "last"],//逗號(hào)風(fēng)格,換行時(shí)在行首還是行尾
"complexity": [0, 11],//循環(huán)復(fù)雜度
"computed-property-spacing": [0, "never"],//是否允許計(jì)算后的鍵名什么的
"consistent-return": 0,//return 后面是否允許省略
"consistent-this": [2, "that"],//this別名
"constructor-super": 0,//非派生類不能調(diào)用super缰雇,派生類必須調(diào)用super
"curly": [2, "all"],//必須使用 if(){} 中的{}
"default-case": 2,//switch語(yǔ)句最后必須有default
"dot-location": 0,//對(duì)象訪問(wèn)符的位置入偷,換行的時(shí)候在行首還是行尾
"dot-notation": [0, { "allowKeywords": true }],//避免不必要的方括號(hào)
"eol-last": 0,//文件以單一的換行符結(jié)束
"eqeqeq": 2,//必須使用全等
"func-names": 0,//函數(shù)表達(dá)式必須有名字
"func-style": [0, "declaration"],//函數(shù)風(fēng)格,規(guī)定只能使用函數(shù)聲明/函數(shù)表達(dá)式
"generator-star-spacing": 0,//生成器函數(shù)*的前后空格
"guard-for-in": 0,//for in循環(huán)要用if語(yǔ)句過(guò)濾
"handle-callback-err": 0,//nodejs 處理錯(cuò)誤
"id-length": 0,//變量名長(zhǎng)度
"indent": [2, 4],//縮進(jìn)風(fēng)格
"init-declarations": 0,//聲明時(shí)必須賦初值
"key-spacing": [0, { "beforeColon": false, "afterColon": true }],//對(duì)象字面量中冒號(hào)的前后空格
"lines-around-comment": 0,//行前/行后備注
"max-depth": [0, 4],//嵌套塊深度
"max-len": [0, 80, 4],//字符串最大長(zhǎng)度
"max-nested-callbacks": [0, 2],//回調(diào)嵌套深度
"max-params": [0, 3],//函數(shù)最多只能有3個(gè)參數(shù)
"max-statements": [0, 10],//函數(shù)內(nèi)最多有幾個(gè)聲明
"new-cap": 2,//函數(shù)名首行大寫必須使用new方式調(diào)用械哟,首行小寫必須用不帶new方式調(diào)用
"new-parens": 2,//new時(shí)必須加小括號(hào)
"newline-after-var": 2,//變量聲明后是否需要空一行
"object-curly-spacing": [0, "never"],//大括號(hào)內(nèi)是否允許不必要的空格
"object-shorthand": 0,//強(qiáng)制對(duì)象字面量縮寫語(yǔ)法
"one-var": 1,//連續(xù)聲明
"operator-assignment": [0, "always"],//賦值運(yùn)算符 += -=什么的
"operator-linebreak": [2, "after"],//換行時(shí)運(yùn)算符在行尾還是行首
"padded-blocks": 0,//塊語(yǔ)句內(nèi)行首行尾是否要空行
"prefer-const": 0,//首選const
"prefer-spread": 0,//首選展開運(yùn)算
"prefer-reflect": 0,//首選Reflect的方法
"quotes": [1, "single"],//引號(hào)類型 `` "" ''
"quote-props":[2, "always"],//對(duì)象字面量中的屬性名是否強(qiáng)制雙引號(hào)
"radix": 2,//parseInt必須指定第二個(gè)參數(shù)
"id-match": 0,//命名檢測(cè)
"require-yield": 0,//生成器函數(shù)必須有yield
"semi": [2, "always"],//語(yǔ)句強(qiáng)制分號(hào)結(jié)尾
"semi-spacing": [0, {"before": false, "after": true}],//分號(hào)前后空格
"sort-vars": 0,//變量聲明時(shí)排序
"space-after-keywords": [0, "always"],//關(guān)鍵字后面是否要空一格
"space-before-blocks": [0, "always"],//不以新行開始的塊{前面要不要有空格
"space-before-function-paren": [0, "always"],//函數(shù)定義時(shí)括號(hào)前面要不要有空格
"space-in-parens": [0, "never"],//小括號(hào)里面要不要有空格
"space-infix-ops": 0,//中綴操作符周圍要不要有空格
"space-return-throw-case": 2,//return throw case后面要不要加空格
"space-unary-ops": [0, { "words": true, "nonwords": false }],//一元運(yùn)算符的前/后要不要加空格
"spaced-comment": 0,//注釋風(fēng)格要不要有空格什么的
"strict": 2,//使用嚴(yán)格模式
"use-isnan": 2,//禁止比較時(shí)使用NaN疏之,只能用isNaN()
"valid-jsdoc": 0,//jsdoc規(guī)則
"valid-typeof": 2,//必須使用合法的typeof的值
"vars-on-top": 2,//var必須放在作用域頂部
"wrap-iife": [2, "inside"],//立即執(zhí)行函數(shù)表達(dá)式的小括號(hào)風(fēng)格
"wrap-regex": 0,//正則表達(dá)式字面量用小括號(hào)包起來(lái)
"yoda": [2, "never"]//禁止尤達(dá)條件
示例
//steps-01:安裝依賴
//steps-02:編寫配置
//steps-03:運(yùn)行命令
專題
其解析器
解析器表
- Esprima
- Babel-ESLint - A wrapper around the Babel parser that makes it compatible with ESLint.
- typescript-eslint-parser(Experimental) - A parser that converts TypeScript into an ESTree-compatible form so it can be used in ESLint. The goal is to allow TypeScript files to be parsed by ESLint (though not necessarily pass all ESLint rules).
//.eslintrc
{
"parser": "esprima",
"rules": {
"semi": "error"
}
}
特定環(huán)境
An environment defines global variables that are predefined. The available environments are:
環(huán)境列表
-
browser
- browser global variables. -
node
- Node.js global variables and Node.js scoping. -
commonjs
- CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack). -
shared-node-browser
- Globals common to both Node.js and Browser. -
es6
- enable all ECMAScript 6 features except for modules (this automatically sets theecmaVersion
parser option to 6). -
worker
- web workers global variables. -
amd
- definesrequire()
anddefine()
as global variables as per the amd spec. -
mocha
- adds all of the Mocha testing global variables. -
jasmine
- adds all of the Jasmine testing global variables for version 1.3 and 2.0. -
jest
- Jest global variables. -
phantomjs
- PhantomJS global variables. -
protractor
- Protractor global variables. -
qunit
- QUnit global variables. -
jquery
- jQuery global variables. -
prototypejs
- Prototype.js global variables. -
shelljs
- ShellJS global variables. -
meteor
- Meteor global variables. -
mongo
- MongoDB global variables. -
applescript
- AppleScript global variables. -
nashorn
- Java 8 Nashorn global variables. -
serviceworker
- Service Worker global variables. -
atomtest
- Atom test helper globals. -
embertest
- Ember test helper globals. -
webextensions
- WebExtensions globals. -
greasemonkey
- GreaseMonkey globals.
指定環(huán)境
方式1:在腳本中
/* eslint-env node, mocha */
方式2:配置文件
//.eslintrc
{
"env": {
"browser": true,
"node": true
}
}
方式3:于命令行
eslint --env node
Environments can be specified inside of a file, in configuration files or using the
--env
command line flag.
全局變量
The no-undef rule will warn on variables that are accessed but not defined within the same file. If you are using global variables inside of a file then it’s worthwhile to define those globals so that ESLint will not warn about their usage.
指定變量
方式1:在腳本中
//可讀可寫
/* global var1, var2 */
//變量只讀
/* global var1:false, var2:false */
方式2:配置文件
//.eslintrc
{
"globals": {
"var1": false,
"var2": false
}
}
方式3:于命令行
eslint --global var1 var2
You can define global variables either using comments inside of a file or in the configuration file
使用插件
ESLint supports the use of third-party plugins. Before using the plugin you have to install it using npm.
指定插件
方式1:配置文件
//.eslintrc
{
"plugins": [
"plugin1",
"eslint-plugin-plugin2"
]
}
方式2:于命令行
eslint --plugin plugin1 eslint-plugin-plugin2
To configure plugins inside of a configuration file, use the
plugins
key, which contains a list of plugin names. Theeslint-plugin-
prefix can be omitted from the plugin name.
使用規(guī)則
ESLint comes with a large number of rules.
規(guī)則列表
取值說(shuō)明
"off" or 0 - turn the rule off
"warn" or 1 - turn the rule on as a warning (doesn’t affect exit code)
"error" or 2 - turn the rule on as an error (exit code is 1 when triggered)
指定規(guī)則
方式1:在腳本中
//字符模式
/* eslint eqeqeq: "off", curly: "error" */
//數(shù)字模式
/* eslint eqeqeq: 0, curly: 2 */
//額外選項(xiàng)
/* eslint quotes: ["error", "double"], curly: 2 */
//于某插件
/* eslint "plugin1/rule1": "error" */
//關(guān)閉校驗(yàn)
/* eslint-disable */
//開啟校驗(yàn)
/* eslint-enable */
//關(guān)某規(guī)則
/* eslint-disable no-alert */
方式2:配置文件
//.eslintrc
{
"plugins": [
"plugin1"
],
"rules": {
"eqeqeq": "off",
"curly": "error",
"quotes": ["error", "double"],
"plugin1/rule1": "error"
}
}
方式3:于命令行
eslint --rule
You can modify which rules your project uses either using configuration comments or configuration files.
共享設(shè)置
ESLint supports adding shared settings into configuration file. You can add settings
object to ESLint configuration file and it will be supplied to every rule that will be executed.
指定共享
方式1:配置文件
//.eslintrc
{
"settings": {
"sharedData": "Hello"
}
}
配置文件
文件查找
The first way to use configuration files is via .eslintrc.*
and package.json
files. ESLint will automatically look for them in the directory of the file to be linted, and in successive parent directories all the way up to the root directory of the filesystem (unless root: true
is specified).
使用配置
方式1:于命令行
eslint -c myconfig.json myfiletotest.js
方式2:
If you are using one configuration file and want ESLint to ignore any
.eslintrc.*
files, make sure to use--no-eslintrc
along with the-c
flag.
文件格式
JavaScript
- use .eslintrc.js
and export an object containing your configuration.
YAML
- use .eslintrc.yaml
or .eslintrc.yml
to define the configuration structure.
JSON
- use .eslintrc.json
to define the configuration structure. ESLint’s JSON files also allow JavaScript-style comments.
Deprecated
- use .eslintrc
, which can be either JSON or YAML.
package.json
- create an eslintConfig
property in your package.json file and define your configuration there.
權(quán)重順序
f there are multiple configuration files in the same directory, ESLint will only use one. The priority order is:
1暇咆、.eslintrc.js
2锋爪、.eslintrc.yaml
3、.eslintrc.yml
4爸业、.eslintrc.json
5其骄、.eslintrc
6、package.json
配置層疊
When using .eslintrc.*
and package.json
files for configuration, you can take advantage of configuration cascading.The configuration cascade works by using the closest .eslintrc file
to the file being linted as the highest priority, then any configuration files in the parent directory, and so on.
your-project
├── .eslintrc
├── lib
│ └── source.js
└─┬ tests
├── .eslintrc
└── test.js
it means : When you run ESLint on this project, all files in lib/ will use the .eslintrc
file at the root of the project as their configuration. When ESLint traverses into the tests/
directory, it will then use your-project/tests/.eslintrc
in addition to your-project/.eslintrc
. So your-project/tests/test.js
is linted based on the combination of the two .eslintrc
files in its directory hierarchy, with the closest one taking priority. In this way, you can have project-level ESLint settings and also have directory-specific overrides.
關(guān)往父找
By default, ESLint will look for configuration files in all parent folders up to the root directory. This can be useful if you want all of your projects to follow a certain convention, but can sometimes lead to unexpected results. To limit ESLint to a specific project, place "root": true
inside the eslintConfig
field of the package.json
file or in the .eslintrc.*
file at your project’s root level. ESLint will stop looking in parent folders once it finds a configuration with "root": true
.
方式1:
//.eslintrc
{
"root": true
}
方式2:
//package.json
{
"eslintConfig":{
"root": true
}
}
層疊權(quán)重
The complete configuration hierarchy, from highest precedence to lowest precedence, is as follows:
某腳本內(nèi)
/eslint-disable/ and /eslint-enable/
/global/
/eslint/
/eslint-env/
于命令行:
--global
--rule
--env
-c, --config
配置文件:
1扯旷、.eslintrc.*
or package.json
file in same directory as linted file
2拯爽、Continue searching for .eslintrc and package.json files in ancestor directories (parent has highest precedence, then grandparent, etc.), up to and including the root directory or until a config with "root": true is found.
環(huán)境目錄:
In the absence of any configuration from (1) thru (3), fall back to a personal default configuration in~/.eslintrc
.
配置擴(kuò)展
A configuration file can extend the set of enabled rules from base configurations.
設(shè)置方式
The extends
property value is either:
a string that specifies a configuration
an array of strings: each additional configuration extends the preceding configurations
{
"extends": "eslint:recommended",
"rules": {
// enable additional rules
"indent": ["error", 4],
"linebreak-style": ["error", "unix"],
"quotes": ["error", "double"],
"semi": ["error", "always"],
// override default options for rules from base configurations
"comma-dangle": ["error", "always"],
"no-cond-assign": ["error", "always"],
// disable rules from base configurations
"no-console": "off",
}
}
配置擴(kuò)展還有更多的用法,待展開钧忽。
忽略文件
//.eslintignore
/node_modules/*
/bower_components/*
build/*
!build/index.js
配置注釋
Both the JSON and YAML configuration file formats support comments (package.json
files should not include them).
{
"env": {
"browser": true
},
"rules": {
// Override our default settings just for this directory
"eqeqeq": "warn",
"strict": "off"
}
}
You can use JavaScript-style comments or YAML-style comments in either type of file and ESLint will safely ignore them.