Eslint Standard Lite - 小而美的代码规范
本工具拥有以下特点
- 少量配置 即可拥有统一的代码风格
- 自动代码格式化 轻松拥有整洁代码
- 开箱即用 不用维护 .eslintrc, .jshintrc, or .jscsrc
安装
npm install eslint-standard-lite --save-dev
使用
添加配置
"scripts": {
"lint": "standard --verbose | snazzy || exit 0"
}
执行命令
npm run lint
为什么规则这么多,这么详细?
多人开发,避免不同代码格式引起的冲突和不必要的代码变更,规则过于宽松达不到代码一致的效果,多人编辑同一份代码,就会造成A同学编辑后是tab缩进,B同学编辑后是空格缩进,类似这样的问题。
针对老项目应用规范会有什么问题?
- 改动量大,大部分都是格式调整,很琐碎,无论是改动之后的CR,还是回归测试都是巨大的成本,短期收益小。
- 不同的项目有不同的全局变量,怎么办。
- 不同的项目有不同的构建流程,有的使用webpack,有的使用gulp,有的使用rollup,如何搭配使用。
针对问题1:
可以使用本规范的几种能力来辅助解决。
- 推荐逐步推进规范,可以通过配置忽略文件,来逐步推进,可以在package.json里添加 standard.ignore 属性来配置
"standard": {
"ignore": [
"**/foo/",
"/lib/a/",
"/lib/b/",
"template.js"
]
}
- 在package.json里添加如下配置,大部分的琐碎改动可以通过执行
npm run fix
来自动修复
"scripts": {
"fix": "standard --fix || exit 0"
}
针对问题2:
- 默认已有的全局变量
document
、navigator
、window
、AlipayJSBridge
、ant
、$
- 也可以自定义全局变量,在 package.json 里添加 standard.globals 属性来配置
"standard": {
"globals": [
"React",
"Vue",
"Page"
]
}
针对问题3:
以gulp为例,可以使用如下配置,这样只有在校验通过之后才会执行gulp
命令
"scripts": {
"build": "standard --verbose | snazzy || exit 0 && gulp"
}
- 为什么要添加
exit 0
? 这是为了阻止显示默认的无用报错信息。
细则
-
使用两个空格进行缩进。
eslint:
indent
{console;} -
除需要转义的情况外,字符串统一使用单引号。
eslint:
quotes
console;; -
不要定义未使用的变量。
eslint:
no-unused-vars
{var result = ; // ✗ avoid} -
关键字后面加空格。
eslint:
keyword-spacing
if condition ... // ✓ okifcondition ... // ✗ avoid -
函数声明时括号与函数名间加空格。
eslint:
space-before-function-paren
{ ... } // ✓ ok{ ... } // ✗ avoid; // ✓ ok; // ✗ avoid -
使用
===
替代==
。(这条会抛出警告)
例外:obj == null
可以用来检查null || undefined
。eslint:
eqeqeq
if name === 'John' // ✓ okif name == 'John' // ✗ avoidif name !== 'John' // ✓ okif name != 'John' // ✗ avoid -
字符串拼接操作符 (Infix operators) 之间要留空格。
eslint:
space-infix-ops
// ✓ okvar x = 2;var message = 'hello, ' + name + '!';// ✗ avoidvar x=2;var message = 'hello, '+name+'!'; -
逗号后面加空格。
eslint:
comma-spacing
// ✓ okvar list = 1 2 3 4;{ ... }// ✗ avoidvar list = 1234;{ ... } -
else 关键字要与花括号保持在同一行。
eslint:
brace-style
// ✓ okif condition// ...else// ...// ✗ avoidif condition// ...else// ... -
多行 if 语句的的括号不能省。
eslint:
curly
// ✓ okif optionsquiet !== true console;// ✓ okif optionsquiet !== trueconsole;// ✗ avoidif optionsquiet !== trueconsole; -
不要丢掉异常处理中
err
参数。eslint:
handle-callback-err
// ✓ ok// ✗ avoid; -
使用浏览器全局变量时加上
window.
前缀。
Exceptions are:document
,console
andnavigator
.eslint:
no-undef
window; // ✓ ok -
不允许有连续多行空行。
eslint:
no-multiple-empty-lines
// ✓ okvar value = 'hello world';console;// ✗ avoidvar value = 'hello world';console; -
对于三元运算符
?
和:
与他们所负责的代码处于同一行eslint:
operator-linebreak
// ✓ okvar location = envdevelopment ? 'localhost' : 'www.api.com';// ✓ okvar location = envdevelopment;? 'localhost': 'www.api.com'// ✗ avoidvar location = envdevelopment ?'localhost' :'www.api.com'; -
每个 var 关键字单独声明一个变量。
eslint:
one-var
// ✓ okvar silent = true;var verbose = true;// ✗ avoidvar silent = true verbose = true;// ✗ avoidvar silent = trueverbose = true; -
条件语句中赋值语句使用括号包起来。这样使得代码更加清晰可读,而不会认为是将条件判断语句的全等号(
===
)错写成了等号(=
)。eslint:
no-cond-assign
// ✓ okwhile m = text// ...// ✗ avoidwhile m = text// ... -
单行代码块两边加空格。
eslint:
block-spacing
{return true} // ✗ avoid{ return true } // ✓ ok -
对于变量和函数名统一使用驼峰命名法。
eslint:
camelcase
{ } // ✗ avoid{ } // ✓ okvar my_var = 'hello'; // ✗ avoidvar myVar = 'hello'; // ✓ ok -
不允许有多余的行末逗号。
eslint:
comma-dangle
var obj =message: 'hello' // ✗ avoid -
始终将逗号置于行末。
eslint:
comma-style
var obj =foo: 'foo'bar: 'bar' // ✗ avoidvar obj =foo: 'foo'bar: 'bar' // ✓ ok -
点号操作符须与属性需在同一行。
eslint:
dot-location
console; // ✗ avoidconsole; // ✓ ok -
文件末尾留一空行。
elint:
eol-last
-
函数调用时标识符与括号间不留间隔。
eslint:
func-call-spacing
console; // ✗ avoidconsole; // ✓ ok -
键值对当中冒号与值之间要留空白。
eslint:
key-spacing
var obj = 'key' : 'value' // ✗ avoidvar obj = 'key' :'value' // ✗ avoidvar obj = 'key':'value' // ✗ avoidvar obj = 'key': 'value' // ✓ ok -
构造函数要以大写字母开头。
eslint:
new-cap
{}var dog = ; // ✗ avoid{}var dog = ; // ✓ ok -
无参的构造函数调用时要带上括号。
eslint:
new-parens
{}var dog = ; // ✗ avoidvar dog = ; // ✓ ok -
对象中定义了存值器,一定要对应的定义取值器。
eslint:
accessor-pairs
var person ={ // ✗ avoidthisname = value;}var person ={thisname = value;}{ // ✓ okreturn thisname;} -
子类的构造器中一定要调用
super
eslint:
constructor-super
{super; // ✗ avoid}{super; // ✓ ok} -
使用数组字面量而不是构造器。
eslint:
no-array-constructor
var nums = 1 2 3; // ✗ avoidvar nums = 1 2 3; // ✓ ok -
避免使用
arguments.callee
和arguments.caller
。eslint:
no-caller
{if n <= 0 return;argumentscalleen - 1; // ✗ avoid}{if n <= 0 return;;} -
避免对类名重新赋值。
eslint:
no-class-assign
{}Dog = 'Fido'; // ✗ avoid -
避免修改使用
const
声明的变量。eslint:
no-const-assign
const score = 100;score = 125; // ✗ avoid -
避免使用常量作为条件表达式的条件(循环语句除外)。
eslint:
no-constant-condition
if false // ✗ avoid// ...if x === 0 // ✓ ok// ...while true // ✓ ok// ... -
正则中不要使用控制符。
eslint:
no-control-regex
var pattern = /\x1f/; // ✗ avoidvar pattern = /\x20/; // ✓ ok -
不要使用
debugger
。eslint:
no-debugger
{debugger; // ✗ avoidreturn a + b;} -
不要对变量使用
delete
操作。eslint:
no-delete-var
var name;delete name; // ✗ avoid -
不要定义冗余的函数参数。
eslint:
no-dupe-args
{ // ✗ avoid// ...}{ // ✓ ok// ...} -
类中不要定义冗余的属性。
eslint:
no-dupe-class-members
{}{} // ✗ avoid -
对象字面量中不要定义重复的属性。
eslint:
no-dupe-keys
var user =name: 'Jane Doe'name: 'John Doe' // ✗ avoid -
switch
语句中不要定义重复的case
分支。eslint:
no-duplicate-case
-
同一模块有多个导入时一次性写完。
eslint:
no-duplicate-imports
;; // ✗ avoid; // ✓ ok -
正则中不要使用空字符。
eslint:
no-empty-character-class
const myRegex = /^abc[]/; // ✗ avoidconst myRegex = /^abc[a-z]/; // ✓ ok -
不要解构空值。
eslint:
no-empty-pattern
const a: = foo; // ✗ avoidconst a: b = foo; // ✓ ok -
不要使用
eval()
。eslint:
no-eval
; // ✗ avoidvar result = userpropName; // ✓ ok -
catch
中不要对错误重新赋值。eslint:
no-ex-assign
try// ...catch ee = 'new value'; // ✗ avoidtry// ...catch econst newVal = 'new value'; // ✓ ok -
不要扩展原生对象。
eslint:
no-extend-native
Objectprototypeage = 21; // ✗ avoid -
避免多余的函数上下文绑定。
eslint:
no-extra-bind
const name = {;}; // ✗ avoidconst name = {this;}; // ✓ ok -
避免不必要的布尔转换。
eslint:
no-extra-boolean-cast
const result = true;if !!result // ✗ avoid// ...const result = true;if result // ✓ ok// ... -
不要使用多余的括号包裹函数。
eslint:
no-extra-parens
const myFunc = { }; // ✗ avoidconst myFunc = { }; // ✓ ok -
switch
一定要使用break
来将条件分支正常中断。eslint:
no-fallthrough
-
不要省去小数点前面的0。
eslint:
no-floating-decimal
const discount = 5; // ✗ avoidconst discount = 05; // ✓ ok -
避免对声明过的函数重新赋值。
eslint:
no-func-assign
{ }myFunc = myOtherFunc; // ✗ avoid -
不要对全局只读对象重新赋值。
eslint:
no-global-assign
window = {}; // ✗ avoid -
注意隐式的
eval()
。eslint:
no-implied-eval
; // ✗ avoid; // ✓ ok -
嵌套的代码块中禁止再定义函数。
eslint:
no-inner-declarations
if authenticated{} // ✗ avoid -
不要向
RegExp
构造器传入非法的正则表达式。eslint:
no-invalid-regexp
RegExp'[a-z'; // ✗ avoidRegExp'[a-z]'; // ✓ ok -
不要使用非法的空白符。
eslint:
no-irregular-whitespace
/*<NBSP>*/{} // ✗ avoid -
禁止使用
__iterator__
。eslint:
no-iterator
Fooprototype {}; // ✗ avoid -
外部变量不要与对象属性重名。
eslint:
no-label-var
var score = 100;{score: 50 // ✗ avoid} -
不要使用标签语句。
eslint:
no-labels
label:while truebreak label; // ✗ avoid -
不要书写不必要的嵌套代码块。
eslint:
no-lone-blocks
{// ✗ avoid;}{; // ✓ ok} -
不要混合使用空格与制表符作为缩进。
eslint:
no-mixed-spaces-and-tabs
-
除了缩进,不要使用多个空格。
eslint:
no-multi-spaces
const id = 1234; // ✗ avoidconst id = 1234; // ✓ ok -
不要使用多行字符串。
eslint:
no-multi-str
const message = 'Hello \world'; // ✗ avoid -
new
创建对象实例后需要赋值给变量。eslint:
no-new
; // ✗ avoidconst character = ; // ✓ ok -
禁止使用
Function
构造器。eslint:
no-new-func
var sum = 'a' 'b' 'return a + b'; // ✗ avoid -
禁止使用
Object
构造器。eslint:
no-new-object
let config = ; // ✗ avoid -
禁止使用
new require
。eslint:
no-new-require
const myModule = 'my-module'; // ✗ avoid -
禁止使用
Symbol
构造器。eslint:
no-new-symbol
const foo = 'foo'; // ✗ avoid -
禁止使用原始包装器。
eslint:
no-new-wrappers
const message = 'hello'; // ✗ avoid -
不要将全局对象的属性作为函数调用。
eslint:
no-obj-calls
const math = Math; // ✗ avoid -
不要使用八进制字面量。
eslint:
no-octal
const num = 042; // ✗ avoidconst num = '042'; // ✓ ok -
字符串字面量中也不要使用八进制转义字符。
eslint:
no-octal-escape
const copyright = 'Copyright \251'; // ✗ avoid -
使用
__dirname
和__filename
时尽量避免使用字符串拼接。eslint:
no-path-concat
const pathToFile = __dirname + '/app.js'; // ✗ avoidconst pathToFile = path; // ✓ ok -
使用
getPrototypeOf
来替代__proto__
。eslint:
no-proto
const foo = obj__proto__; // ✗ avoidconst foo = Object; // ✓ ok -
不要重复声明变量。
eslint:
no-redeclare
let name = 'John';let name = 'Jane'; // ✗ avoidlet name = 'John';name = 'Jane'; // ✓ ok -
正则中避免使用多个空格。
eslint:
no-regex-spaces
const regexp = /test value/; // ✗ avoidconst regexp = /test {3}value/; // ✓ okconst regexp = /test value/; // ✓ ok -
return 语句中的赋值必需有括号包裹。
eslint:
no-return-assign
{return result = a + b; // ✗ avoid}{return result = a + b; // ✓ ok} -
避免将变量赋值给自己。
eslint:
no-self-assign
name = name; // ✗ avoid -
避免将变量与自己进行比较操作。
esint:
no-self-compare
if score === score {} // ✗ avoid -
避免使用逗号操作符。
eslint:
no-sequences
if !!test {} // ✗ avoid -
不要随意更改关键字的值。
eslint:
no-shadow-restricted-names
let undefined = 'value'; // ✗ avoid -
禁止使用稀疏数组(Sparse arrays)。
eslint:
no-sparse-arrays
let fruits = 'apple' 'orange'; // ✗ avoid -
不要使用制表符。
eslint:
no-tabs
-
正确使用 ES6 中的字符串模板。
eslint:
no-template-curly-in-string
const message = 'Hello ${name}'; // ✗ avoidconst message = `Hello `; // ✓ ok -
使用
this
前请确保super()
已调用。eslint:
no-this-before-super
{thislegs = 4; // ✗ avoidsuper;} -
用
throw
抛错时,抛出Error
对象而不是字符串。eslint:
no-throw-literal
throw 'error'; // ✗ avoidthrow 'error'; // ✓ ok -
行末不留空格。
eslint:
no-trailing-spaces
-
不要使用
undefined
来初始化变量。eslint:
no-undef-init
let name = undefined; // ✗ avoidlet name;name = 'value'; // ✓ ok -
循环语句中注意更新循环变量。
eslint:
no-unmodified-loop-condition
for let i = 0; i < itemslength; j++ ... // ✗ avoidfor let i = 0; i < itemslength; i++ ... // ✓ ok -
如果有更好的实现,尽量不要使用三元表达式。
eslint:
no-unneeded-ternary
let score = val ? val : 0; // ✗ avoidlet score = val || 0; // ✓ ok -
return
,throw
,continue
和break
后不要再跟代码。eslint:
no-unreachable
{return true;console; // ✗ avoid} -
finally
代码块中不要再改变程序执行流程。eslint:
no-unsafe-finally
try// ...catch e// ...finallyreturn 42; // ✗ avoid -
关系运算符的左值不要做取反操作。
eslint:
no-unsafe-negation
if !key in obj {} // ✗ avoid -
避免不必要的
.call()
和.apply()
。eslint:
no-useless-call
sum; // ✗ avoid -
避免使用不必要的计算值作对象属性。
eslint:
no-useless-computed-key
const user = 'name': 'John Doe' ; // ✗ avoidconst user = name: 'John Doe' ; // ✓ ok -
禁止多余的构造器。
eslint:
no-useless-constructor
{ // ✗ avoid} -
禁止不必要的转义。
eslint:
no-useless-escape
let message = 'Hell\o'; // ✗ avoid -
import, export 和解构操作中,禁止赋值到同名变量。
eslint:
no-useless-rename
; // ✗ avoid; // ✓ ok -
属性前面不要加空格。
eslint:
no-whitespace-before-property
user name // ✗ avoidusername // ✓ ok -
禁止使用
with
。eslint:
no-with
with val ... // ✗ avoid -
对象属性换行时注意统一代码风格。
eslint:
object-property-newline
const user =name: 'Jane Doe' age: 30username: 'jdoe86' // ✗ avoid;const user = name: 'Jane Doe' age: 30 username: 'jdoe86' ; // ✓ okconst user =name: 'Jane Doe'age: 30username: 'jdoe86'; // ✓ ok -
代码块中避免多余留白。
eslint:
padded-blocks
if user// ✗ avoidconst name = ;if userconst name = ; // ✓ ok -
展开运算符与它的表达式间不要留空白。
eslint:
rest-spread-spacing
; // ✗ avoid; // ✓ ok -
遇到分号时空格要后留前不留。
eslint:
semi-spacing
for let i = 0 ;i < itemslength ;i++ ... // ✗ avoidfor let i = 0; i < itemslength; i++ ... // ✓ ok -
代码块首尾留空格。
eslint:
space-before-blocks
if admin... // ✗ avoidif admin ... // ✓ ok -
圆括号间不留空格。
eslint:
space-in-parens
; // ✗ avoid; // ✓ ok -
一元运算符后面跟一个空格。
eslint:
space-unary-ops
typeof!admin; // ✗ avoidtypeof !admin; // ✓ ok -
注释首尾留空格。
eslint:
spaced-comment
//comment // ✗ avoid// comment // ✓ ok/*comment*/ // ✗ avoid/* comment */ // ✓ ok -
模板字符串中变量前后不加空格。
eslint:
template-curly-spacing
const message = `Hello, `; // ✗ avoidconst message = `Hello, `; // ✓ ok -
检查
NaN
的正确姿势是使用isNaN()
。eslint:
use-isnan
if price === NaN // ✗ avoidif // ✓ ok -
用合法的字符串跟
typeof
进行比较操作。eslint:
valid-typeof
typeof name === 'undefimed' // ✗ avoidtypeof name === 'undefined' // ✓ ok -
自调用匿名函数 (IIFEs) 使用括号包裹。
eslint:
wrap-iife
const getName = { }; // ✗ avoidconst getName = { }; // ✓ okconst getName = { }; // ✓ ok -
yield *
中的*
前后都要有空格。eslint:
yield-star-spacing
; // ✗ avoid; // ✓ ok -
请书写优雅的条件语句(avoid Yoda conditions)。
eslint:
yoda
if 42 === age // ✗ avoidif age === 42 // ✓ ok
关于分号
-
使用分号。
eslint:
semi
window; // ✓ okwindow // ✗ avoid -
不要使用
(
,[
, or`
等作为一行的开始。在没有分号的情况下代码压缩后会导致报错,而坚持这一规范则可避免出错。eslint:
no-unexpected-multiline
// ✓ ok; {window;};// ✗ avoid{window;}