ESLint javascript格式要求

首行缩进2个空格
eslint:  indent
functionhello (name) {
  console.log('hi', name)
}
字符串使用单引号(除了避免转义)
eslint:  quotes
console.log('hello there')
$("<div class='box'>")
禁止出现未使用的变量
eslint:  no-unused-vars
functionmyFunction () {
  var result =something()   // ✗ avoid
}
关键字后增加一个空格
eslint:  keyword-spacing
if (condition) { ... }   // ✓ ok
if(condition) { ... }    // ✗ avoid
函数声明的圆括号前增加一个空格
functionname (arg) { ... }   // ✓ ok
functionname(arg) { ... }    // ✗ avoid
run(function () { ... })      // ✓ ok
run(function() { ... })       // ✗ avoid
使用严格运算符===替代相等运算符==
除了obj == null 允许检查 null || undefined
eslint:  eqeqeq
if (name === 'John')   // ✓ ok
if (name == 'John')    // ✗ avoid
if (name !== 'John')   // ✓ ok
if (name != 'John')    // ✗ avoid
中缀运算符必须使用一个空格分开
eslint:  space-infix-ops
// ✓ ok
var x = 2
var message = 'hello, ' + name + '!'
// ✗ avoid
var x=2
var message = 'hello, '+name+'!'
逗号后面紧跟一个空格
eslint:  comma-spacing
// ✓ ok
var list = [1, 2, 3, 4]
function greet (name, options) { ... }
// ✗ avoid
var list = [1,2,3,4]
function greet (name,options) { ... }
else和后括号保持在同一行
eslint:  brace-style
// ✓ ok
if (condition) {
  // ...
} else {
  // ...
}
// ✗ avoid
if (condition) {
  // ...
}
else {
  // ...
}
多行if声明,使用花括号
eslint:  curly
// ✓ ok
if (options.quiet !== true) console.log('done')
// ✓ ok
if (options.quiet !== true) {
  console.log('done')
}
// ✗ avoid
if (options.quiet !== true)
  console.log('done')
函数参数err必须处理
// ✓ ok
run(function (err) {
  if (err) throw err
  window.alert('done')
})
// ✗ avoid
run(function (err) {
  window.alert('done')
})
必须使用浏览器全局参数window.前缀,除了document,console,navigator
eslint:  no-undef
window.alert('hi')   // ✓ ok
多个空白行是不允许的
// ✓ ok
var value = 'hello world'
console.log(value)
// ✗ avoid
var value = 'hello world'


console.log(value)
使用多行书写三元表达式时,?和:放在所属行
eslint:  operator-linebreak
// ✓ ok
var location = env.development ? 'localhost' : 'www.api.com'

// ✓ ok
var location = env.development
  ? 'localhost'
  : 'www.api.com'

// ✗ avoid
var location = env.development ?
  'localhost' :
  'www.api.com'
使用var声明时,一个声明使用一个表达式
eslint:  one-var
// ✓ ok
var silent = true
var verbose = true

// ✗ avoid
var silent = true, verbose = true

// ✗ avoid
var silent = true,
    verbose = true
使用额外的括号包裹额外的赋值
eslint:  no-cond-assign
// ✓ ok
while ((m = text.match(expr))) {
  // ...
}

// ✗ avoid
while (m = text.match(expr)) {
  // ...
}
单行块里首尾增加空格
eslint:  block-spacing
  function foo () {return true}    // ✗ avoid
  function foo () { return true }  // ✓ ok
变量和函数命名使用驼峰法
eslint:  camelcase
  function my_function () { }    // ✗ avoid
  function myFunction () { }     // ✓ ok

  var my_var = 'hello'           // ✗ avoid
  var myVar = 'hello'            // ✓ ok
禁止尾部加逗号
eslint:  comma-dangle
  var obj = {
    message: 'hello',   // ✗ avoid
  }
逗号放在当前行的末尾
eslint:  comma-style
  var obj = {
    foo: 'foo'
    ,bar: 'bar'   // ✗ avoid
  }

  var obj = {
    foo: 'foo',
    bar: 'bar'   // ✓ ok
  }
点号和属性保持同一行
eslint:  dot-location
  console.
    log('hello')  // ✗ avoid

  console
    .log('hello') // ✓ ok
文件以换行符结束
elint:  eol-last
标示符和请求之间不能有空格
eslint:  func-call-spacing
console.log ('hello') // ✗ avoid
console.log('hello')  // ✓ ok
键值对表达式的冒号和值之间要有空格
eslint:  key-spacing
var obj = { 'key' : 'value' }    // ✗ avoid
var obj = { 'key' :'value' }     // ✗ avoid
var obj = { 'key':'value' }      // ✗ avoid
var obj = { 'key': 'value' }     // ✓ ok
构造方法的名字首字母大写
eslint:  new-cap
function animal () {}
var dog = new animal()    // ✗ avoid

function Animal () {}
var dog = new Animal()    // ✓ ok
无参构造方法调用时必须有圆括号
eslint:  new-parens
function Animal () {}
var dog = new Animal    // ✗ avoid
var dog = new Animal()  // ✓ ok
一个对象有setter方法的前提必须先订单getter方法
eslint:  accessor-pairs
var person = {
  set name (value) {    // ✗ avoid
    this.name = value
  }
}

var person = {
  set name (value) {
    this.name = value
  },
  get name () {         // ✓ ok
    return this.name
  }
}
派生类(继承类)的构造才能调用super
eslint:  constructor-super
class Dog {
  constructor () {
    super()   // ✗ avoid
  }
}

class Dog extends Mammal {
  constructor () {
    super()   // ✓ ok
  }
}
使用数组字面量代替数组构造函数
var nums = new Array(1, 2, 3)   // ✗ avoid
var nums = [1, 2, 3]            // ✓ ok
避免使用arguments.callee和arguments.caller
eslint:  no-caller
function foo (n) {
  if (n <= 0) return

  arguments.callee(n - 1)   // ✗ avoid
}

function foo (n) {
  if (n <= 0) return

  foo(n - 1)
}
避免修改类声明变量
eslint:  no-class-assign
class Dog {}
Dog = 'Fido'    // ✗ avoid
避免修改const声明的变量
eslint:  no-const-assign
const score = 100
score = 125       // ✗ avoid
避免在条件中使用常量表达式(循环例外)
if (false) {    // ✗ avoid
  // ...
}

if (x === 0) {  // ✓ ok
  // ...
}

while (true) {  // ✓ ok
  // ...
}
正则表达式中禁止使用控制字符
eslint:  no-control-regex
var pattern = /\x1f/    // ✗ avoid
var pattern = /\x20/    // ✓ ok
不要使用debugger表达式
eslint:  no-debugger
function sum (a, b) {
  debugger      // ✗ avoid
  return a + b
}
不要在变量上使用delete运算符
eslint:  no-delete-var
var name
delete name     // ✗ avoid
函数定义时不要使用重复的参数
eslint:  no-dupe-args
function sum (a, b, a) {  // ✗ avoid
  // ...
}

function sum (a, b, c) {  // ✓ ok
  // ...
}
类成员中不能出现重复的名字
class Dog {
  bark () {}
  bark () {}    // ✗ avoid
}
对象字面量中不能出现重复键值
eslint:  no-dupe-keys
var user = {
  name: 'Jane Doe',
  name: 'John Doe'    // ✗ avoid
}
switch表达式中不能出现重复的case值
eslint:  no-duplicate-case
switch (id) {
  case 1:
    // ...
  case 1:     // ✗ avoid
}
每一个模块只能有一个import表达式
import { myFunc1 } from 'module'
import { myFunc2 } from 'module'          // ✗ avoid

import { myFunc1, myFunc2 } from 'module' // ✓ ok
正则表达式中不能有空的字母类
const myRegex = /^abc[]/      // ✗ avoid
const myRegex = /^abc[a-z]/   // ✓ ok
不能有空的结构模式
eslint:  no-empty-pattern
const { a: {} } = foo         // ✗ avoid
const { a: { b } } = foo      // ✓ ok
禁止使用eval()
eslint:  no-eval
eval( "var result = user." + propName ) // ✗ avoid
var result = user[propName]             // ✓ ok
catch子句中不能重新分配异常
eslint:  no-ex-assign
try {
  // ...
} catch (e) {
  e = 'new value'             // ✗ avoid
}

try {
  // ...
} catch (e) {
  const newVal = 'new value'  // ✓ ok
}
不能扩展本地对象
eslint:  no-extend-native
Object.prototype.age = 21     // ✗ avoid
避免不必要的函数绑定
eslint:  no-extra-bind
const name = function () {
  getName()
}.bind(user)    // ✗ avoid

const name = function () {
  this.getName()
}.bind(user)    // ✓ ok
避免不必要的布尔操作
const result = true
if (!!result) {   // ✗ avoid
  // ...
}

const result = true
if (result) {     // ✓ ok
  // ...
}
避免不必要的括号包裹函数表达式
eslint:  no-extra-parens
const myFunc = (function () { })   // ✗ avoid
const myFunc = function () { }     // ✓ ok
switch的case表达式处理中使用break阻止继续下沉
eslint:  no-fallthrough
switch (filter) {
  case 1:
    doSomething()    // ✗ avoid
  case 2:
    doSomethingElse()
}

switch (filter) {
  case 1:
    doSomething()
    break           // ✓ ok
  case 2:
    doSomethingElse()
}

switch (filter) {
  case 1:
    doSomething()
    // fallthrough  // ✓ ok
  case 2:
    doSomethingElse()
}
不能有浮点小数
const discount = .5      // ✗ avoid
const discount = 0.5     // ✓ ok
避免重新分配函数声明
eslint:  no-func-assign
function myFunc () { }
myFunc = myOtherFunc    // ✗ avoid
避免重新分配只读全局变量
eslint:  no-global-assign
window = {}     // ✗ avoid
不使用隐式的函数
eslint:  no-implied-eval
setTimeout("alert('Hello world')")                   // ✗ avoid
setTimeout(function () { alert('Hello world') })     // ✓ ok
嵌套块中不能有函数声明
if (authenticated) {
  function setAuthUser () {}    // ✗ avoid
}
正则构造方法中不能出现无效的正则表达式
eslint:  no-invalid-regexp
RegExp('[a-z')    // ✗ avoid
RegExp('[a-z]')   // ✓ ok
不能出现不规则的空白
function myFunc () /*<NBSP>*/{}   // ✗ avoid
不能使用_iterator_
eslint:  no-iterator
Foo.prototype.__iterator__ = function () {}   // ✗ avoid
标签名不能和局部变量重名
eslint:  no-label-var
var score = 100
function game () {
  score: 50         // ✗ avoid
}
不能有标签声明
eslint:  no-labels
label:
  while (true) {
    break label     // ✗ avoid
  }
不能有无用的嵌套块
eslint:  no-lone-blocks
function myFunc () {
  {                   // ✗ avoid
    myOtherFunc()
  }
}

function myFunc () {
  myOtherFunc()       // ✓ ok
}
缩进时避免混合空格和tabs
除了缩进不要使用多个空格
eslint:  no-multi-spaces
const id =    1234    // ✗ avoid
const id = 1234       // ✓ ok
禁止多行的字符串
eslint:  no-multi-str
const message = 'Hello \
                 world'     // ✗ avoid
没有给变量赋值对象时不要使用new
eslint:  no-new
new Character()                     // ✗ avoid
const character = new Character()   // ✓ ok
不要使用Function构造方法
eslint:  no-new-func
var sum = new Function('a', 'b', 'return a + b')    // ✗ avoid
不要使用Object构造方法
eslint:  no-new-object
let config = new Object()   // ✗ avoid
不要使用new require
eslint:  no-new-require
const myModule = new require('my-module')    // ✗ avoid
不要使用Symbol构造方法
eslint:  no-new-symbol
const foo = new Symbol('foo')   // ✗ avoid
不要使用原始包装器实例
eslint:  no-new-wrappers
const message = new String('hello')   // ✗ avoid
不要调用全局对象属性作为函数
eslint:  no-obj-calls
const math = Math()   // ✗ avoid
不要使用八进制字符
eslint:  no-octal
const num = 042     // ✗ avoid
const num = '042'   // ✓ ok
字符串中不要使用八进制转义序列
eslint:  no-octal-escape
const copyright = 'Copyright \251'  // ✗ avoid
字符串拼接时避免使用__dirname和__filename
eslint:  no-path-concat
const pathToFile = __dirname + '/app.js'            // ✗ avoid
const pathToFile = path.join(__dirname, 'app.js')   // ✓ ok
避免使用__proto__,使用getPrototypeOf来代替
eslint:  no-proto
const foo = obj.__proto__               // ✗ avoid
const foo = Object.getPrototypeOf(obj)  // ✓ ok
不要重复声明变量
eslint:  no-redeclare
let name = 'John'
let name = 'Jane'     // ✗ avoid

let name = 'John'
name = 'Jane'         // ✓ ok
正则表达式中避免出现多个空格
eslint:  no-regex-spaces
const regexp = /test   value/   // ✗ avoid

const regexp = /test {3}value/  // ✓ ok
const regexp = /test value/     // ✓ ok
return表达式中赋值时使用括号包裹
eslint:  no-return-assign
function sum (a, b) {
  return result = a + b     // ✗ avoid
}

function sum (a, b) {
  return (result = a + b)   // ✓ ok
}
避免给变量本身赋值
eslint:  no-self-assign
name = name   // ✗ avoid
避免变量本身比较
esint:  no-self-compare
if (score === score) {}   // ✗ avoid
避免使用逗号表达式
eslint:  no-sequences
if (doSomething(), !!test) {}   // ✗ avoid
受限关键字不能使用
let undefined = 'value'     // ✗ avoid
不允许稀疏数组出现
eslint:  no-sparse-arrays
let fruits = ['apple',, 'orange']       // ✗ avoid
Tabs禁止使用
eslint:  no-tabs
常规字符串中不能包含模板占位符
const message = 'Hello ${name}'   // ✗ avoid
const message = `Hello ${name}`   // ✓ ok
super()必须在this之前调用
class Dog extends Animal {
  constructor () {
    this.legs = 4     // ✗ avoid
    super()
  }
}
只能抛出Error对象
eslint:  no-throw-literal
throw 'error'               // ✗ avoid
throw new Error('error')    // ✓ ok
行尾不允许有空格
eslint:  no-trailing-spaces
不能使用undefined初始化
eslint:  no-undef-init
let name = undefined    // ✗ avoid

let name
name = 'value'          // ✓ ok
循环语句中循环条件要变更
for (let i = 0; i < items.length; j++) {...}    // ✗ avoid
for (let i = 0; i < items.length; i++) {...}    // ✓ ok
有更简单的形式存在时,不要使用三元表达式
let score = val ? val : 0     // ✗ avoid
let score = val || 0          // ✓ ok
return, throw, continue, break后不要有代码
eslint:  no-unreachable
function doSomething () {
  return true
  console.log('never called')     // ✗ avoid
}
finally语句块中不要有控制流语句
eslint:  no-unsafe-finally
try {
  // ...
} catch (e) {
  // ...
} finally {
  return 42     // ✗ avoid
}
关系运算符的左操作数不能否定
eslint:  no-unsafe-negation
if (!key in obj) {}       // ✗ avoid
避免不必要的使用.call()和.apply()
eslint:  no-useless-call
sum.call(null, 1, 2, 3)   // ✗ avoid
在对象中避免使用不必要的计算属性键
const user = { ['name']: 'John Doe' }   // ✗ avoid
const user = { name: 'John Doe' }       // ✓ ok
不必要的构造方法
class Car {
  constructor () {      // ✗ avoid
  }
}
避免不必要的转义
eslint:  no-useless-escape
let message = 'Hell\o'  // ✗ avoid
导入、导出和解构赋值,不要赋相同的名字
eslint:  no-useless-rename
import { config as config } from './config'     // ✗ avoid
import { config } from './config'               // ✓ ok
属性前不要有空格
user .name      // ✗ avoid
user.name       // ✓ ok
不要使用with表达式
eslint:  no-with
with (val) {...}    // ✗ avoid
对象属性的行分配要保持一致
const user = {
  name: 'Jane Doe', age: 30,
  username: 'jdoe86'            // ✗ avoid
}

const user = { name: 'Jane Doe', age: 30, username: 'jdoe86' }    // ✓ ok

const user = {
  name: 'Jane Doe',
  age: 30,
  username: 'jdoe86'
}  
语句块中不要有空隙
eslint:  padded-blocks
if (user) {
                            // ✗ avoid
  const name = getName()

}

if (user) {
  const name = getName()    // ✓ ok
}
传播运算符的表达式不能有空格
fn(... args)    // ✗ avoid
fn(...args)     // ✓ ok
分号前不能有空格,后必须有空格
eslint:  semi-spacing
for (let i = 0 ;i < items.length ;i++) {...}    // ✗ avoid
for (let i = 0; i < items.length; i++) {...}    // ✓ ok
块语句前要有一个空格
if (admin){...}     // ✗ avoid
if (admin) {...}    // ✓ ok
圆括号内不能有空格
eslint:  space-in-parens
getName( name )     // ✗ avoid
getName(name)       // ✓ ok
一元运算符后要有空格
eslint:  space-unary-ops
typeof!admin        // ✗ avoid
typeof !admin        // ✓ ok
注释内要有空格
eslint:  spaced-comment
//comment           // ✗ avoid
// comment          // ✓ ok

/*comment*/         // ✗ avoid
/* comment */       // ✓ ok
模板字符串中不能有空格
const message = `Hello, ${ name }`    // ✗ avoid
const message = `Hello, ${name}`      // ✓ ok
检查NaN时使用isNaN()
eslint:  use-isnan
if (price === NaN) { }      // ✗ avoid
if (isNaN(price)) { }       // ✓ ok
typeof必须和有效的字符串比较
eslint:  valid-typeof
typeof name === 'undefimed'     // ✗ avoid
typeof name === 'undefined'     // ✓ ok
直接调用函数表达式必要要被包装
eslint:  wrap-iife
const getName = function () { }()     // ✗ avoid

const getName = (function () { }())   // ✓ ok
const getName = (function () { })()   // ✓ ok
yield*表达式中的*前后都应有一个空格
eslint:  yield-star-spacing
yield* increment()    // ✗ avoid
yield * increment()   // ✓ ok
避免使用尤达条件
eslint:  yoda
if (42 === age) { }    // ✗ avoid
if (age === 42) { }    // ✓ ok
分号
不使用分号的情况
eslint:  semi
window.alert('hi')   // ✓ ok
window.alert('hi');  // ✗ avoid
开始行不要以(,[,`开头,否则前面要加分号
// ✓ ok
;(function () {
  window.alert('ok')
}())

// ✗ avoid
(function () {
  window.alert('ok')
}())

// ✓ ok
;[1, 2, 3].forEach(bar)

// ✗ avoid
[1, 2, 3].forEach(bar)
// ✓ ok
;`hello`.indexOf('o')

// ✗ avoid
`hello`.indexOf('o')


转载于:https://www.cnblogs.com/archermeng/p/7537082.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值