standard 代碼規範

前端代碼靜態檢查規範


  • 使用兩個空格進行縮進

    eslint: indent

    function hello (name) {
    
      console.log('hi', name)
    
    }
    
    
  • 除需要轉義的情況外,字符串統一使用單引號

    eslint: quotes

    console.log('hello there')
    
    $("<div class='box'>")
    
    
  • 不要定義未使用的變量

    eslint: no-unused-vars

    function myFunction () {
    
      var result = something()   
    
    }
    
    
  • 關鍵字後面加空格

    eslint: keyword-spacing

    if (condition) { ... }   
    
    if(condition) { ... }    
    
    
  • 函數聲明時括號與函數名間加空格

    eslint: space-before-function-paren

    function name (arg) { ... }   
    
    function name(arg) { ... }    
    
    run(function () { ... })      
    
    run(function() { ... })       
    
    
  • 始終使用 === 替代 ==
    例外: obj == null 可以用來檢查 null || undefined

    eslint: eqeqeq

    if (name === 'John')   
    
    if (name == 'John')    
    
    
    if (name !== 'John')   
    
    if (name != 'John')    
    
    
  • 字符串拼接操作符 (Infix operators) 之間要留空格。

    eslint: space-infix-ops

    var x = 2
    
    var message = 'hello, ' + name + '!'
    
    
    var x=2
    
    var message = 'hello, '+name+'!'
    
    
  • 逗號後面加空格

    eslint: comma-spacing

    var list = [1, 2, 3, 4]
    
    function greet (name, options) { ... }
    
    
    var list = [1,2,3,4]
    
    function greet (name,options) { ... }
    
    
  • else 關鍵字要與花括號保持在同一行。

    eslint: brace-style

    if (condition) {
    
    } else {
    
    }
    
    
  • 多行 if 語句的的括號不能省。

    eslint: curly

    if (options.quiet !== true) console.log('done')
    
    
    if (options.quiet !== true) {
    
      console.log('done')
    
    }
    
    
    if (options.quiet !== true)
    
      console.log('done')
    
    
  • 不要丟掉異常處理中err參數。

    eslint: handle-callback-err

    run(function (err) {
    
      if (err) throw err
    
      window.alert('done')
    
    })
    
    
    run(function (err) {
    
      window.alert('done')
    
    })
    
    
  • 使用瀏覽器全局變量時加上 window. 前綴。
    documentconsolenavigator 除外。

    eslint: no-undef

  • 不允許有連續多行空行

    eslint: no-multiple-empty-lines

    var value = 'hello world'
    
    console.log(value)
    
    
    var value = 'hello world'
    
    console.log(value)
    
    
  • 對於三元運算符 ?: 與他們所負責的代碼處於同一行

    eslint: operator-linebreak

    var location = env.development ? 'localhost' : 'www.api.com'
    
    var location = env.development
    
      ? 'localhost'
    
      : 'www.api.com'
    
    var location = env.development ?
    
      'localhost' :
    
      'www.api.com'
    
    
  • 每個 var 關鍵字單獨聲明一個變量。

    eslint: one-var

    var silent = true
    
    var verbose = true
    
    var silent = true, verbose = true
    
    var silent = true,
    
        verbose = true
    
    
  • 條件語句中賦值語句使用括號包起來。這樣使得代碼更加清晰可讀,而不會認爲是將條件判斷語句的全等號(===)錯寫成了等號(=)。

    eslint: no-cond-assign

    while ((m = text.match(expr))) {
    
    }
    
    while (m = text.match(expr)) {
    
    }
    
    
  • 單行代碼塊兩邊加空格

    eslint: block-spacing

      function foo () {return true}    
    
      function foo () { return true }  
    
    
  • 對於變量和函數名統一使用駝峯命名法

    eslint: camelcase

      function my_function () { }    
    
      function myFunction () { }     
    
      var my_var = 'hello'           
    
      var myVar = 'hello'            
    
    
  • 不允許有多餘的行末逗號

    eslint: comma-dangle

      var obj = {
    
        message: 'hello',   
    
      }
    
    
  • 始終將逗號置於行末

    eslint: comma-style

      var obj = {
    
        foo: 'foo'
    
        ,bar: 'bar'   
    
      }
    
      var obj = {
    
        foo: 'foo',
    
        bar: 'bar'   
    
      }
    
    
  • 點號操作符須與屬性需在同一行

    eslint: dot-location

      console.
    
        log('hello')  
    
      console
    
        .log('hello') 
    
    
  • 文件末尾留一空行

    eslint: eol-last

  • 函數調用時標識符與括號間不留間隔

    eslint: func-call-spacing

    console.log ('hello') 
    
    console.log('hello')  
    
    
  • 鍵值對當中冒號與值之間要留空白

    eslint: key-spacing

    var obj = { 'key' : 'value' }    
    
    var obj = { 'key' :'value' }     
    
    var obj = { 'key':'value' }      
    
    var obj = { 'key': 'value' }     
    
    
  • 構造函數要以大寫字母開頭

    eslint: new-cap

    function animal () {}
    
    var dog = new animal()    
    
    function Animal () {}
    
    var dog = new Animal()    
    
    
  • 無參的構造函數調用時要帶上括號

    eslint: new-parens

    function Animal () {}
    
    var dog = new Animal    
    
    var dog = new Animal()  
    
    
  • 對象中定義了存值器,一定要對應的定義取值器

    eslint: accessor-pairs

    var person = {
    
      set name (value) {    
    
        this._name = value
    
      }
    
    }
    
    var person = {
    
      set name (value) {
    
        this._name = value
    
      },
    
      get name () {         
    
        return this._name
    
      }
    
    }
    
    
  • 子類的構造器中一定要調用 super

    eslint: constructor-super

    class Dog {
    
      constructor () {
    
        super()   
    
      }
    
    }
    
    class Dog extends Mammal {
    
      constructor () {
    
        super()   
    
      }
    
    }
    
    
  • 使用數組字面量而不是構造器

    eslint: no-array-constructor

    var nums = new Array(1, 2, 3)   
    
    var nums = [1, 2, 3]            
    
    
  • 避免使用 arguments.calleearguments.caller

    eslint: no-caller

    function foo (n) {
    
      if (n <= 0) return
    
      arguments.callee(n - 1)   
    
    }
    
    function foo (n) {
    
      if (n <= 0) return
    
      foo(n - 1)
    
    }
    
    
  • 避免對類名重新賦值

    eslint: no-class-assign

  • 避免修改使用 const 聲明的變量

    eslint: no-const-assign

    const score = 100
    
    score = 125       
    
    
  • 避免使用常量作爲條件表達式的條件(循環語句除外)

    eslint: no-constant-condition

    if (false) {    
    
    }
    
    if (x === 0) {  
    
    }
    
    while (true) {  
    
    }
    
    
  • 正則中不要使用控制符

    eslint: no-control-regex

    var pattern = /\x1f/    
    
    var pattern = /\x20/    
    
    
  • 不要使用 debugger

    eslint: no-debugger

    function sum (a, b) {
    
      debugger      
    
      return a + b
    
    }
    
    
  • 不要對變量使用 delete 操作

    eslint: no-delete-var

  • 不要定義冗餘的函數參數

    eslint: no-dupe-args

    function sum (a, b, a) {  
    
    }
    
    function sum (a, b, c) {  
    
    }
    
    
  • 類中不要定義冗餘的屬性

    eslint: no-dupe-class-members

    class Dog {
    
      bark () {}
    
      bark () {}    
    
    }
    
    
  • 對象字面量中不要定義重複的屬性

    eslint: no-dupe-keys

    var user = {
    
      name: 'Jane Doe',
    
      name: 'John Doe'    
    
    }
    
    
  • switch 語句中不要定義重複的 case 分支

    eslint: no-duplicate-case

    switch (id) {
    
      case 1:
    
      case 1:     
    
    }
    
    
  • 同一模塊有多個導入時一次性寫完

    eslint: no-duplicate-imports

    import { myFunc1 } from 'module'
    
    import { myFunc2 } from 'module'          
    
    import { myFunc1, myFunc2 } from 'module' 
    
    
  • 正則中不要使用空字符

    eslint: no-empty-character-class

    const myRegex = /^abc[]/      
    
    const myRegex = /^abc[a-z]/   
    
    
  • 不要解構空值

    eslint: no-empty-pattern

    const { a: {} } = foo         
    
    const { a: { b } } = foo      
    
    
  • 不要使用 eval()

    eslint: no-eval

    eval( "var result = user." + propName ) 
    
    var result = user[propName]             
    
    
  • catch 中不要對錯誤重新賦值

    eslint: no-ex-assign

    try {
    
    } catch (e) {
    
      e = 'new value'             
    
    }
    
    try {
    
    } catch (e) {
    
      const newVal = 'new value'  
    
    }
    
    
  • 不要擴展原生對象

    eslint: no-extend-native

    Object.prototype.age = 21     
    
    
  • 避免多餘的函數上下文綁定

    eslint: no-extra-bind

    const name = function () {
    
      getName()
    
    }.bind(user)    
    
    const name = function () {
    
      this.getName()
    
    }.bind(user)    
    
    
  • 避免不必要的布爾轉換

    eslint: no-extra-boolean-cast

    const result = true
    
    if (!!result) {   
    
    }
    
    const result = true
    
    if (result) {     
    
    }
    
    
  • 不要使用多餘的括號包裹函數

    eslint: no-extra-parens

    const myFunc = (function () { })   
    
    const myFunc = function () { }     
    
    
  • switch 一定要使用 break 來將條件分支正常中斷

    eslint: no-fallthrough

    switch (filter) {
    
      case 1:
    
        doSomething()    
    
      case 2:
    
        doSomethingElse()
    
    }
    
    switch (filter) {
    
      case 1:
    
        doSomething()
    
        break           
    
      case 2:
    
        doSomethingElse()
    
    }
    
    switch (filter) {
    
      case 1:
    
        doSomething()
    
      case 2:
    
        doSomethingElse()
    
    }
    
    
  • 不要省去小數點前面的 0

    eslint: no-floating-decimal

    const discount = .5      
    
    const discount = 0.5     
    
    
  • 避免對聲明過的函數重新賦值

    eslint: no-func-assign

    function myFunc () { }
    
    myFunc = myOtherFunc    
    
    
  • 不要對全局只讀對象重新賦值

    eslint: no-global-assign

  • 注意隱式的 eval()

    eslint: no-implied-eval

    setTimeout("alert('Hello world')")                   
    
    setTimeout(function () { alert('Hello world') })     
    
    
  • 嵌套的代碼塊中禁止再定義函數

    eslint: no-inner-declarations

    if (authenticated) {
    
      function setAuthUser () {}    
    
    }
    
    
  • 不要向 RegExp 構造器傳入非法的正則表達式

    eslint: no-invalid-regexp

    RegExp('[a-z')    
    
    RegExp('[a-z]')   
    
    
  • 不要使用非法的空白符

    eslint: no-irregular-whitespace

  • 禁止使用 __iterator__

    eslint: no-iterator

    Foo.prototype.__iterator__ = function () {}   
    
    
  • 外部變量不要與對象屬性重名

    eslint: no-label-var

    var score = 100
    
    function game () {
    
      score: while (true) {      
    
        score -= 10
    
        if (score > 0) continue score
    
        break
    
      }
    
    }
    
    
  • 不要使用標籤語句

    eslint: no-labels

    label:
    
      while (true) {
    
        break label     
    
      }
    
    
  • 不要書寫不必要的嵌套代碼塊

    eslint: no-lone-blocks

    function myFunc () {
    
      {                   
    
        myOtherFunc()
    
      }
    
    }
    
    function myFunc () {
    
      myOtherFunc()       
    
    }
    
    
  • 不要混合使用空格與製表符作爲縮進

    eslint: no-mixed-spaces-and-tabs

  • 除了縮進,不要使用多個空格

    eslint: no-multi-spaces

    const id =    1234    
    
    const id = 1234       
    
    
  • 不要使用多行字符串

    eslint: no-multi-str

    const message = 'Hello \
    
                     world'     
    
    
  • new 創建對象實例後需要賦值給變量

    eslint: no-new

    new Character()                     
    
    const character = new Character()   
    
    
  • 禁止使用 Function 構造器

    eslint: no-new-func

    var sum = new Function('a', 'b', 'return a + b')    
    
    
  • 禁止使用 Object 構造器

    eslint: no-new-object

    let config = new Object()   
    
    
  • 禁止使用 new require

    eslint: no-new-require

    const myModule = new require('my-module')    
    
    
  • 禁止使用 Symbol 構造器

    eslint: no-new-symbol

    const foo = new Symbol('foo')   
    
    
  • 禁止使用原始包裝器

    eslint: no-new-wrappers

    const message = new String('hello')   
    
    
  • 不要將全局對象的屬性作爲函數調用

    eslint: no-obj-calls

  • 不要使用八進制字面量

    eslint: no-octal

    const octal = 042         
    
    const decimal = 34        
    
    const octalString = '042' 
    
    
  • 字符串字面量中也不要使用八進制轉義字符

    eslint: no-octal-escape

    const copyright = 'Copyright \251'  
    
    
  • 使用 __dirname__filename 時儘量避免使用字符串拼接

    eslint: no-path-concat

    const pathToFile = __dirname + '/app.js'            
    
    const pathToFile = path.join(__dirname, 'app.js')   
    
    
  • 使用 getPrototypeOf 來替代 __proto__

    eslint: no-proto

    const foo = obj.__proto__               
    
    const foo = Object.getPrototypeOf(obj)  
    
    
  • 不要重複聲明變量

    eslint: no-redeclare

    let name = 'John'
    
    let name = 'Jane'     
    
    let name = 'John'
    
    name = 'Jane'         
    
    
  • 正則中避免使用多個空格

    eslint: no-regex-spaces

    const regexp = /test   value/   
    
    const regexp = /test {3}value/  
    
    const regexp = /test value/     
    
    
  • return 語句中的賦值必需有括號包裹

    eslint: no-return-assign

    function sum (a, b) {
    
      return result = a + b     
    
    }
    
    function sum (a, b) {
    
      return (result = a + b)   
    
    }
    
    
  • 避免將變量賦值給自己

    eslint: no-self-assign

  • 避免將變量與自己進行比較操作

    esint: no-self-compare

  • 避免使用逗號操作符

    eslint: no-sequences

    if (doSomething(), !!test) {}   
    
    
  • 不要隨意更改關鍵字的值

    eslint: no-shadow-restricted-names

  • 禁止使用稀疏數組(Sparse arrays)

    eslint: no-sparse-arrays

    let fruits = ['apple',, 'orange']       
    
    
  • 不要使用製表符

    eslint: no-tabs

  • 正確使用 ES6 中的字符串模板

    eslint: no-template-curly-in-string

    const message = 'Hello ${name}'   
    
    const message = `Hello ${name}`   
    
    
  • 使用 this 前請確保 super() 已調用

    eslint: no-this-before-super

    class Dog extends Animal {
    
      constructor () {
    
        this.legs = 4     
    
        super()
    
      }
    
    }
    
    
  • throw 拋錯時,拋出 Error 對象而不是字符串

    eslint: no-throw-literal

    throw 'error'               
    
    throw new Error('error')    
    
    
  • 行末不留空格

    eslint: no-trailing-spaces

  • 不要使用 undefined 來初始化變量

    eslint: no-undef-init

    let name = undefined    
    
    let name
    
    name = 'value'          
    
    
  • 循環語句中注意更新循環變量

    eslint: no-unmodified-loop-condition

    for (let i = 0; i < items.length; j++) {...}    
    
    for (let i = 0; i < items.length; i++) {...}    
    
    
  • 如果有更好的實現,儘量不要使用三元表達式

    eslint: no-unneeded-ternary

    let score = val ? val : 0     
    
    let score = val || 0          
    
    
  • returnthrowcontinuebreak 後不要再跟代碼

    eslint: no-unreachable

    function doSomething () {
    
      return true
    
      console.log('never called')     
    
    }
    
    
  • finally 代碼塊中不要再改變程序執行流程

    eslint: no-unsafe-finally

    try {
    
    } catch (e) {
    
    } finally {
    
      return 42     
    
    }
    
    
  • 關係運算符的左值不要做取反操作

    eslint: no-unsafe-negation

  • 避免不必要的 .call().apply()

    eslint: no-useless-call

  • 避免使用不必要的計算值作對象屬性

    eslint: no-useless-computed-key

    const user = { ['name']: 'John Doe' }   
    
    const user = { name: 'John Doe' }       
    
    
  • 禁止多餘的構造器

    eslint: no-useless-constructor

    class Car {
    
      constructor () {      
    
      }
    
    }
    
    
  • 禁止不必要的轉義

    eslint: no-useless-escape

  • import, export 和解構操作中,禁止賦值到同名變量

    eslint: no-useless-rename

    import { config as config } from './config'     
    
    import { config } from './config'               
    
    
  • 屬性前面不要加空格

    eslint: no-whitespace-before-property

  • 禁止使用 with

    eslint: no-with

  • 對象屬性換行時注意統一代碼風格

    eslint: object-property-newline

    const user = {
    
      name: 'Jane Doe', age: 30,
    
      username: 'jdoe86'            
    
    }
    
    const user = { name: 'Jane Doe', age: 30, username: 'jdoe86' }    
    
    const user = {
    
      name: 'Jane Doe',
    
      age: 30,
    
      username: 'jdoe86'
    
    }                                                                 
    
    
  • 代碼塊中避免多餘留白

    eslint: padded-blocks

    if (user) {
    
      const name = getName()
    
    }
    
    if (user) {
    
      const name = getName()    
    
    }
    
    
  • 展開運算符與它的表達式間不要留空白

    eslint: rest-spread-spacing

  • 遇到分號時空格要後留前不留

    eslint: semi-spacing

    for (let i = 0 ;i < items.length ;i++) {...}    
    
    for (let i = 0; i < items.length; i++) {...}    
    
    
  • 代碼塊首尾留空格

    eslint: space-before-blocks

    if (admin){...}     
    
    if (admin) {...}    
    
    
  • 圓括號間不留空格

    eslint: space-in-parens

    getName( name )     
    
    getName(name)       
    
    
  • 一元運算符後面跟一個空格

    eslint: space-unary-ops

    typeof!admin        
    
    typeof !admin        
    
    
  • 註釋首尾留空格

    eslint: spaced-comment

  • 模板字符串中變量前後不加空格

    eslint: template-curly-spacing

    const message = `Hello, ${ name }`    
    
    const message = `Hello, ${name}`      
    
    
  • 檢查 NaN 的正確姿勢是使用 isNaN()

    eslint: use-isnan

    if (price === NaN) { }      
    
    if (isNaN(price)) { }       
    
    
  • 用合法的字符串跟 typeof 進行比較操作

    eslint: valid-typeof

    typeof name === 'undefimed'     
    
    typeof name === 'undefined'     
    
    
  • 自調用匿名函數 (IIFEs) 使用括號包裹

    eslint: wrap-iife

    const getName = function () { }()     
    
    const getName = (function () { }())   
    
    const getName = (function () { })()   
    
    
  • yield * 中的 * 前後都要有空格

    eslint: yield-star-spacing

    yield* increment()    
    
    yield * increment()   
    
    
  • 請書寫優雅的條件語句(avoid Yoda conditions)

    eslint: yoda

    if (42 === age) { }    
    
    if (age === 42) { }    
    
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章