eslint 代碼規範

官網:https://github.com/standard/standard/blob/master/docs/RULES-zhcn.mdjavascript

 

JavaScript Standard Style

English • Español (Latinoamérica) • Français • Italiano (Italian) • 한국어 (Korean) • Português (Brasil) • 簡體中文 (Simplified Chinese) • 繁體中文 (Taiwanese Mandarin)java

js-standard-style

這是 JavaScript standard 代碼規範的全文。git

掌握本規範的最好方法是安裝並在本身的代碼中使用它。github

細則

  • 使用兩個空格進行縮進。正則表達式

    eslint: indentapi

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

    eslint: quotes瀏覽器

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

    eslint: no-unused-varsapp

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

    eslint: keyword-spacing

    if (condition) { ... } // ✓ ok if(condition) { ... } // ✗ avoid
  • 函數聲明時括號與函數名間加空格。

    eslint: space-before-function-paren

    function name (arg) { ... } // ✓ ok function name(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
  • 字符串拼接操做符 (Infix operators) 之間要留空格。

    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參數。

    eslint: handle-callback-err

    // ✓ ok run(function (err) { if (err) throw err window.alert('done') })
    // ✗ avoid run(function (err) { window.alert('done') })
  • 使用瀏覽器全局變量時加上 window. 前綴。
    Exceptions are: documentconsole and navigator.

    eslint: no-undef

    window.alert('hi') // ✓ ok
  • 不容許有連續多行空行。

    eslint: no-multiple-empty-lines

    // ✓ 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
  • 文件末尾留一空行。

    eslint: 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
  • 對象中定義了存值器,必定要對應的定義取值器。

    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 } }
  • 使用數組字面量而不是構造器。

    eslint: no-array-constructor

    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
  • 避免使用常量做爲條件表達式的條件(循環語句除外)。

    eslint: no-constant-condition

    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 // ... }
  • 類中不要定義冗餘的屬性。

    eslint: no-dupe-class-members

    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 }
  • 同一模塊有多個導入時一次性寫完。

    eslint: no-duplicate-imports

    import { myFunc1 } from 'module' import { myFunc2 } from 'module' // ✗ avoid import { myFunc1, myFunc2 } from 'module' // ✓ ok
  • 正則中不要使用空字符。

    eslint: no-empty-character-class

    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
  • 避免沒必要要的布爾轉換。

    eslint: no-extra-boolean-cast

    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 必定要使用 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() }
  • 不要省去小數點前面的0。

    eslint: no-floating-decimal

    const discount = .5 // ✗ avoid const discount = 0.5 // ✓ ok
  • 避免對聲明過的函數從新賦值。

    eslint: no-func-assign

    function myFunc () { } myFunc = myOtherFunc // ✗ avoid
  • 不要對全局只讀對象從新賦值。

    eslint: no-global-assign

    window = {} // ✗ avoid
  • 注意隱式的 eval()

    eslint: no-implied-eval

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

    eslint: no-inner-declarations

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

    eslint: no-invalid-regexp

    RegExp('[a-z') // ✗ avoid RegExp('[a-z]') // ✓ ok
  • 不要使用非法的空白符。

    eslint: no-irregular-whitespace

    function myFunc () /*<NBSP>*/{} // ✗ avoid
  • 禁止使用 __iterator__

    eslint: no-iterator

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

    eslint: no-label-var

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

    eslint: no-labels

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

    eslint: no-lone-blocks

    function myFunc () { { // ✗ avoid myOtherFunc() } } function myFunc () { myOtherFunc() // ✓ ok }
  • 不要混合使用空格與製表符做爲縮進。

    eslint: no-mixed-spaces-and-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
  • 使用 getPrototypeOf 來替代 __proto__

    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
  • 不要隨意更改關鍵字的值。

    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}' // ✗ avoid const message = `Hello ${name}` // ✓ ok
  • 使用 this 前請確保 super() 已調用。

    eslint: no-this-before-super

    class Dog extends Animal { constructor () { this.legs = 4 // ✗ avoid super() } }
  • 用 throw 拋錯時,拋出 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
  • 循環語句中注意更新循環變量。

    eslint: no-unmodified-loop-condition

    for (let i = 0; i < items.length; j++) {...} // ✗ avoid for (let i = 0; i < items.length; i++) {...} // ✓ ok
  • 若是有更好的實現,儘可能不要使用三元表達式。

    eslint: no-unneeded-ternary

    let score = val ? val : 0 // ✗ avoid let score = val || 0 // ✓ ok
  • returnthrowcontinue 和 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
  • 避免使用沒必要要的計算值做對象屬性。

    eslint: no-useless-computed-key

    const user = { ['name']: 'John Doe' } // ✗ avoid const user = { name: 'John Doe' } // ✓ ok
  • 禁止多餘的構造器。

    eslint: no-useless-constructor

    class Car { constructor () { // ✗ avoid } }
  • 禁止沒必要要的轉義。

    eslint: no-useless-escape

    let message = 'Hell\o' // ✗ avoid
  • import, export 和解構操做中,禁止賦值到同名變量。

    eslint: no-useless-rename

    import { config as config } from './config' // ✗ avoid import { config } from './config' // ✓ ok
  • 屬性前面不要加空格。

    eslint: no-whitespace-before-property

    user .name // ✗ avoid user.name // ✓ ok
  • 禁止使用 with

    eslint: no-with

    with (val) {...} // ✗ avoid
  • 對象屬性換行時注意統一代碼風格。

    eslint: object-property-newline

    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' } // ✓ ok
  • 代碼塊中避免多餘留白。

    eslint: padded-blocks

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

    eslint: rest-spread-spacing

    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
  • 代碼塊首尾留空格。

    eslint: space-before-blocks

    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
  • 模板字符串中變量先後不加空格。

    eslint: template-curly-spacing

    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
  • 自調用匿名函數 (IIFEs) 使用括號包裹。

    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
  • 請書寫優雅的條件語句(avoid Yoda conditions)。

    eslint: yoda

    if (42 === age) { } // ✗ avoid if (age === 42) { } // ✓ ok

關於分號

  • 不要使用分號。 (參見:123)

    eslint: semi

    window.alert('hi') // ✓ ok window.alert('hi'); // ✗ avoid
  • 不要使用 ([, or ` 等做爲一行的開始。在沒有分號的狀況下代碼壓縮後會致使報錯,而堅持這一規範則可避免出錯。

    eslint: no-unexpected-multiline

    // ✓ 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')

    備註:上面的寫法只能說聰明過頭了。

    相比更加可讀易懂的代碼,那些看似投巧的寫法是不可取的。

    譬如:

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

    建議的寫法是:

    var nums = [1, 2, 3] nums.forEach(bar)

拓展閱讀

一個值得觀看的視頻:

當前主流的代碼壓縮方案都是基於詞法(AST-based)進行的,因此在處理無分號的代碼時徹底沒有壓力(況且 JavaScript 中分號原本就不是強制的)。

一段摘抄自 "An Open Letter to JavaScript Leaders Regarding Semicolons" 這篇文章的內容:

[自動化插入分號的作法]是安全可依賴的,並且其產出的代碼可以在全部瀏覽器裏很好地運行。 Closure compiler, yuicompressor, packer 還有 jsmin 都能正確地對這樣的代碼進行壓縮處理。並無任何性能相關的問題。

不得不說,Javascript 社區裏的大牛們一直是錯誤的,並不能教給你最佳實踐。真是讓人憂傷啊。 我建議先弄清楚 JS 是怎樣斷句的(還有就是哪些地方看起來斷了其實並無),明白了這個後就能夠隨心寫出漂亮的代碼了。

通常來講, \n 表示語句結束,除非:

  1. 該語句有未閉合的括號, 數組字面量, 對象字面量 或者其餘不能正常結束一條語句的狀況(譬如,以 . 或 , 結尾)
  2. 該語句是 -- 或者 ++ (它會將後面的內容進行自增或減)
  3. 該語句是 for()while()doif() 或者 else 而且沒有 {
  4. 下一行以 [(+*/-,. 或者其餘只會單獨出如今兩塊內容間的二元操做符。

第一條很容易理解。即便在 JSLint 中,也容許 JSON,構造器的括號中,以及使用 var 配合 , 結尾來聲明多個變量等這些情中包含 \n

第二條有點奇葩。 我還想不出誰會(除了這裏用做討論外)寫出 i\n++\nj 這樣的代碼來,不過,順便說一下,這種寫法最後解析的結果是 i; ++j,而不是 i++; j

第三條也容易理解。 if (x)\ny() 等價於 if (x) { y() }。解釋器會向下尋找到代碼塊或一條語句爲止。

; 是條合法的 JavaScript 語句。因此 if(x); 等價於 if(x){},表示 「若是 x 爲真,什麼也不作。」 這種寫法在循環裏面能夠看到,就是當條件判斷與條件更新是同一個方法的時候。 不常見,但也不至於沒據說過吧。

第四條就是常見的 「看,說過要加分號!」 的情形。但這些狀況能夠經過在語句前面加上分號來解決,若是你肯定該語句跟前面的不要緊的話。舉個例子,假如你想這樣:

foo();
[1,2,3].forEach(bar);

那麼徹底能夠這樣來寫:

foo()
;[1,2,3].forEach(bar)

後者的好處是分號比較矚目,一旦習慣後便不再會看到以 ( 和 [ 開頭又不帶分號的語句了。

相關文章
相關標籤/搜索