基于【ESLint+JavaScript Standard Style】標(biāo)準(zhǔn)的VUE/JS/html風(fēng)格指南

小仙男前端代碼風(fēng)格規(guī)范指南v1.0

概述

  • 本規(guī)范是適用于小仙男團(tuán)隊(duì)及前端團(tuán)隊(duì)所搭建的各種前端框架代碼的通用風(fēng)格規(guī)范指南;
  • 使用時(shí),請(qǐng)遵循指南細(xì)則進(jìn)行代碼風(fēng)格約束,并在提交之前確保進(jìn)行代碼風(fēng)格的修正操作;
  • 本規(guī)范參考WEB行業(yè)知名的JavaScript Standard Style 規(guī)范指南。并將在后續(xù)使用過程中,逐步進(jìn)行符合團(tuán)隊(duì)需求的調(diào)整和變更;
  • 掌握本規(guī)范的最好方法是安裝并在自己的代碼中使用它。

安裝與使用

安裝說明

- 兩套方案

按照 Standard官方建議,項(xiàng)目開啟本規(guī)范驗(yàn)證后,將不再需要 ESlintPrettier進(jìn)行代碼格式驗(yàn)證,可減少各種配置文件(方案一)。但為了避免沖突、做好兼容,并保留一定調(diào)整余地,本規(guī)范中有 方案二作為靈活集成方案:

  • 【方案一】(以下稱 Standard版)
    在開啟本規(guī)范驗(yàn)證前,刪除與 ESlintPrettier兩個(gè)插件相關(guān)的依賴注冊(cè)及項(xiàng)目根目錄的相應(yīng)配置文件;
  • 【方案二】(以下稱 ESLint版)
    保留 ESlintPrettier兩個(gè)插件的依賴及配置,在 ESlint中引入eslint-config-standard 配置,并來將個(gè)人配置包裝在上層。

- 方案說明

  • standard規(guī)范制定的目的,就是讓大家都不再花時(shí)間浪費(fèi)在無謂的代碼風(fēng)格之爭(zhēng)上面。因此:
  • 方案一將全盤接受 standard標(biāo)準(zhǔn),并且不支持更改;
  • 方案二則支持在將本規(guī)范集成到 ESlint之中,并支持自定義個(gè)人配置;
  • 本規(guī)范建議:方案一僅做記錄,不支持項(xiàng)目應(yīng)用;各框架選擇方案二實(shí)行。
  • 本規(guī)范強(qiáng)烈建議:為保證團(tuán)隊(duì)規(guī)范的一致性,各項(xiàng)目【不要】自行覆蓋與本規(guī)范相關(guān)的要求。

- 其他說明

  • 對(duì)于開啟本規(guī)范的項(xiàng)目,將會(huì)在項(xiàng)目 package.json中,直接按照 方案一/二預(yù)先配置好相關(guān)操作,前后端開發(fā)人員直接使用即可。

  • 下面全局安裝方案,僅提供前端開發(fā)人員參考,方便在任何地方進(jìn)行規(guī)范檢測(cè)。

  • 全局安裝示例

    npm i -g standard # standard基礎(chǔ)包
    npm i -g eslint-plugin-html@3.2.2 #用于檢測(cè)html或vue文件<script></script>中的代碼,必須是3x版本
    npm i -g snazzy #用戶對(duì)輸出錯(cuò)誤進(jìn)行美化(非強(qiáng)制安裝)
    

【方案一】Standard版(刪除ESlint版方案)

僅做記錄,暫不支持項(xiàng)目應(yīng)用,前期使用請(qǐng)暫時(shí)參考 方案二

- 安裝依賴

  • 項(xiàng)目安裝

    # 進(jìn)入項(xiàng)目目錄
    npm i -D standard # standard基礎(chǔ)包
    npm i -D eslint-plugin-html@3.2.2 #用于檢測(cè)html或vue文件<script></script>中的代碼,必須是3x版本
    npm i -D husky@next #安裝husky git 鉤子,用于強(qiáng)制git提交時(shí)進(jìn)行檢查
    npm i -D snazzy #用戶對(duì)輸出錯(cuò)誤進(jìn)行美化(非強(qiáng)制安裝)
    

- 配置

  • 安裝好依賴資源后,更改項(xiàng)目的 package.json 文件

    // package.json
    {
      "scripts": {
        "standard": "standard ${file} | snazzy",
        "fix": "standard ${file} --fix"
      },
      "standard": {
        // 聲明各種掛載到window上使用的全局變量,避免彈出變量undefined問題
        "globals": [
          "localStorage", "screen", "sessionStorage", "alert", "location", "Notification"
        ]
      },
      "husky": {
        "hooks": {
          "pre-commit": "standard \"src/**/*.{js,vue}\" | snazzy",
        }
      }
    }
    

- 使用

  • 略(暫不支持項(xiàng)目應(yīng)用)

【方案二】ESlitnt版 (集成ESlint版方案)

- 安裝依賴

  • 項(xiàng)目安裝

    # 進(jìn)入項(xiàng)目目錄
    "babel-eslint": "10.1.0",
    "eslint": "^7.0.0",
    "eslint-config-standard": "^14.1.1",
    "eslint-plugin-vue": "^7.0.0",
    "lint-staged": "8.1.5",
    "husky": "1.3.1",npm
    

- 配置

  • 安裝好依賴資源后,更改項(xiàng)目的 package.json 文件

    // package.json
    {
      "scripts": {
        "lint": "eslint --ext .js,.vue src",
        "lintfix": "eslint --fix --ext .js,.vue src",
      },
      "lint-staged": {
        "src/**/*.{js,vue}": [
          "eslint --fix",
          "git add"
        ]
      },
      "husky": {
        "hooks": {
          "pre-commit": "lint-staged"
        }
      }
    }
    
  • 更改項(xiàng)目的 .eslintrc.js 文件

    • rules中調(diào)整部分框架關(guān)閉的規(guī)則,為【試行版】,請(qǐng)勿私自調(diào)整。
    • 具體忽略的 rules,請(qǐng)以各端公共框架的 .eslintrc.js為準(zhǔn)
    // .eslintrc.js
    module.exports = {
      root: true,
      parserOptions: {
        parser: "babel-eslint",
        sourceType: "module",
      },
      env: {
        browser: true,
        node: true,
        es6: true,
      },
      // extends: ['plugin:vue/recommended', 'eslint:recommended'],
      extends: ["plugin:vue/essential", "standard"],
    
      rules: {
        // 【試行版】禁用規(guī)則,請(qǐng)勿自行調(diào)整。
        eqeqeq: ["off"],
        "no-template-curly-in-string": ["off"],
        "vue/script-setup-uses-vars": ["off"],
        "vue/no-mutating-props": ["off"],
        "no-new": ["off"],
      },
    };
    

- 使用

  • 可使用命令行操作,進(jìn)行規(guī)則的檢測(cè)和修復(fù)

    npm run lint # 檢測(cè)項(xiàng)目語法規(guī)范
    npm run lintfix # 修復(fù)不合規(guī)語法
    
  • 除此之外,還可根據(jù)編譯器配置自動(dòng)檢測(cè)和修復(fù)(下文 FAQ以常見的 vscodewebstorm為例介紹)

FAQ

一、常用編譯器配置

(略)

二、如何隱藏某類警告?

  1. JavaScript Standard 代碼規(guī)范底層使用的是 ESLint。所以如果想隱藏某些警告,方法和使用 ESLint 時(shí)一樣。
  2. 隱藏代碼示例
  // 對(duì)某一行禁用所有規(guī)則:
  file = 'I know what I am doing' // eslint-disable-line

  // 或者,只禁用 "no-use-before-define" 這條規(guī)則:
  file = 'I know what I am doing' // eslint-disable-line no-use-before-define

  // 或者,對(duì)多行禁用 "no-use-before-define" 這一規(guī)則:
  /* eslint-disable no-use-before-define */
  console.log('offending code goes here...')
  console.log('offending code goes here...')
  console.log('offending code goes here...')
  /* eslint-enable no-use-before-define */

  // 禁用某個(gè)文件的所有校驗(yàn),直接在文件頭部添加:
  /* eslint-disable camelcase */

三、如何排除某些文件?

  1. ESLint版直接按照 ESLint配置即可
  2. Standard版可以在 package.json中增加 standard.ignore屬性配置:
  "standard": {
    "ignore": [
      "**/out/",
      "tmp.js",
      "......"
    ]
  }

四、使用全局變量,如何避免 "variable is not defined" 的錯(cuò)誤提示?

  1. 經(jīng)過測(cè)試,ESLint版不會(huì)出現(xiàn)這個(gè)問題。
  2. Standard版可以在 package.json中增加 standard.globals屬性配置:
  "standard": {
    "globals": [ "alert", "location", "……" ]
  }

五、如果我不同意某條規(guī)則,可以改嗎?

  1. 說一下整體原則:Standard規(guī)范的目的就是讓大家都不再花時(shí)間浪費(fèi)在無謂的代碼風(fēng)格之爭(zhēng)上面。因此,原生 Standard版不支持任何自定義規(guī)則。
  2. ESLint版由于是在ESLint中引入了 eslint-config-standard插件來實(shí)現(xiàn)規(guī)范約束,因?yàn)榭梢栽?.eslintrc.js文件中覆蓋 rules,但為了框架規(guī)范的一致性,除框架層面統(tǒng)一調(diào)整規(guī)范,各項(xiàng)目請(qǐng)勿私自調(diào)整。
  3. 具體 ESLint版忽略的 rules,請(qǐng)以各端公共框架的 .eslintrc.js為準(zhǔn)

※ 其他FAQ

篇幅有限,其他未盡事宜,請(qǐng)直接查閱Standard官網(wǎng):JavaScript Standard Style

代碼規(guī)范細(xì)則

  • 使用兩個(gè)空格進(jìn)行縮進(jìn)。

    eslint: indent

    function hello (name) {
      console.log('hi', name)
    }
    
  • 除需要轉(zhuǎn)義的情況外,字符串統(tǒng)一使用單引號(hào)。

    eslint: quotes

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

    eslint: no-unused-vars

    function myFunction () {
      var result = something()   // ? avoid
    }
    
  • 關(guān)鍵字后面加空格。

    eslint: keyword-spacing

    if (condition) { ... }   // ? ok
    if(condition) { ... }    // ? avoid
    
  • 函數(shù)聲明時(shí)括號(hào)與函數(shù)名間加空格

    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+'!'
    
  • 逗號(hào)后面加空格

    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 關(guān)鍵字要與花括號(hào)保持在同一行。

    eslint: brace-style

    // ? ok
    if (condition) {
      // ...
    } else {
      // ...
    }
    
    // ? avoid
    if (condition)
    {
      // ...
    }
    else
    {
      // ...
    }
    
  • 多行 if 語句的的括號(hào)不能省。

    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參數(shù)。

    eslint:handle-callback-err

    // ? ok
    run(function (err) {
      if (err) throw err
      window.alert('done')
    })
    
    // ? avoid
    run(function (err) {
      window.alert('done')
    })
    
  • 使用瀏覽器全局變量時(shí)加上 window. 前綴。document、consolenavigator 除外。

    eslint: no-undef

    window.alert('hi')   // ? ok
    
  • 不允許有連續(xù)多行空行

    eslint: no-multiple-empty-lines

    // ? ok
    var value = 'hello world'
    console.log(value)
    
    // ? avoid
    var value = 'hello world'
    
    console.log(value)
    
  • 對(duì)于三元運(yùn)算符 ?: 與他們所負(fù)責(zé)的代碼處于同一行

    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'
    
  • 每個(gè) var 關(guān)鍵字單獨(dú)聲明一個(gè)變量。

    eslint: one-var

    // ? ok
    var silent = true
    var verbose = true
    
    // ? avoid
    var silent = true, verbose = true
    
    // ? avoid
    var silent = true,
        verbose = true
    
  • 條件語句中賦值語句使用括號(hào)包起來。這樣使得代碼更加清晰可讀,而不會(huì)認(rèn)為是將條件判斷語句的全等號(hào)(===)錯(cuò)寫成了等號(hào)(=)。

    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
    
  • 對(duì)于變量和函數(shù)名統(tǒng)一使用駝峰命名法

    eslint: camelcase

    function my_function () { }    // ? avoid
    function myFunction () { }     // ? ok
    
    var my_var = 'hello'           // ? avoid
    var myVar = 'hello'            // ? ok
    
  • 不允許有多余的行末逗號(hào)。

    eslint: comma-dangle

    var obj = {
      message: 'hello',   // ? avoid
    }
    
  • 始終將逗號(hào)置于行末。

    eslint: comma-style

    var obj = {
      foo: 'foo'
      ,bar: 'bar'   // ? avoid
    }
    
    var obj = {
      foo: 'foo',
      bar: 'bar'   // ? ok
    }
    
  • 點(diǎn)號(hào)操作符須與屬性需在同一行

    eslint: dot-location

    console.
      log('hello')  // ? avoid
    
    console
      .log('hello') // ? ok
    
  • 文件末尾留一空行。

    eslint: eol-last

  • 函數(shù)調(diào)用時(shí)標(biāo)識(shí)符與括號(hào)間不留間隔

    eslint:func-call-spacing

    console.log ('hello') // ? avoid
    console.log('hello')  // ? ok
    
  • 鍵值對(duì)當(dāng)中冒號(hào)與值之間要留空白。

    eslint: key-spacing

    var obj = { 'key' : 'value' }    // ? avoid
    var obj = { 'key' :'value' }     // ? avoid
    var obj = { 'key':'value' }      // ? avoid
    var obj = { 'key': 'value' }     // ? ok
    
  • 構(gòu)造函數(shù)要以大寫字母開頭。

    eslint: new-cap

    function animal () {}
    var dog = new animal()    // ? avoid
    
    function Animal () {}
    var dog = new Animal()    // ? ok
    
  • 無參的構(gòu)造函數(shù)調(diào)用時(shí)要帶上括號(hào)

    eslint: new-parens

    function Animal () {}
    var dog = new Animal    // ? avoid
    var dog = new Animal()  // ? ok
    
  • 對(duì)象中定義了存值器,一定要對(duì)應(yīng)的定義取值器。

    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
      }
    }
    
  • 子類的構(gòu)造器中一定要調(diào)用 super

    eslint:constructor-super

    class Dog {
      constructor () {
        super()   // ? avoid
      }
    }
    
    class Dog extends Mammal {
      constructor () {
        super()   // ? ok
      }
    }
    
  • 使用數(shù)組字面量而不是構(gòu)造器。

    eslint:no-array-constructor

    var nums = new Array(1, 2, 3)   // ? avoid
    var nums = [1, 2, 3]            // ? ok
    
  • 避免使用 arguments.calleearguments.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)
    }
    
  • 避免對(duì)類名重新賦值。

    eslint:no-class-assign

    class Dog {}
    Dog = 'Fido'    // ? avoid
    
  • 避免修改使用 const 聲明的變量。

    eslint:no-const-assign

    const score = 100
    score = 125       // ? avoid
    
  • 避免使用常量作為條件表達(dá)式的條件(循環(huán)語句除外)。

    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
    }
    
  • 不要對(duì)變量使用 delete 操作。

    eslint:no-delete-var

    var name
    delete name     // ? avoid
    
  • 不要定義冗余的函數(shù)參數(shù)。

    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
    }
    
  • 對(duì)象字面量中不要定義重復(fù)的屬性。

    eslint: no-dupe-keys

    var user = {
      name: 'Jane Doe',
      name: 'John Doe'    // ? avoid
    }
    
  • switch 語句中不要定義重復(fù)的 case 分支

    eslint:no-duplicate-case

    switch (id) {
      case 1:
        // ...
      case 1:     // ? avoid
    }
    
  • 同一模塊有多個(gè)導(dǎo)入時(shí)一次性寫完。

    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
    
  • 不要解構(gòu)空值

    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 中不要對(duì)錯(cuò)誤重新賦值。

    eslint: no-ex-assign

    try {
      // ...
    } catch (e) {
      e = 'new value'             // ? avoid
    }
    
    try {
      // ...
    } catch (e) {
      const newVal = 'new value'  // ? ok
    }
    
  • 不要擴(kuò)展原生對(duì)象。

    eslint:no-extend-native

    Object.prototype.age = 21     // ? avoid
    
  • 避免多余的函數(shù)上下文綁定。

    eslint:no-extra-bind

    const name = function () {
      getName()
    }.bind(user)    // ? avoid
    
    const name = function () {
      this.getName()
    }.bind(user)    // ? ok
    
  • 避免不必要的布爾轉(zhuǎn)換。

    eslint:no-extra-boolean-cast

    const result = true
    if (!!result) {   // ? avoid
      // ...
    }
    
    const result = true
    if (result) {     // ? ok
      // ...
    }
    
  • 不要使用多余的括號(hào)包裹函數(shù)。

    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()
    }
    
  • 不要省去小數(shù)點(diǎn)前面的0

    eslint:no-floating-decimal

    const discount = .5      // ? avoid
    const discount = 0.5     // ? ok
    
  • 避免對(duì)聲明過的函數(shù)重新賦值。

    eslint:no-func-assign

    function myFunc () { }
    myFunc = myOtherFunc    // ? avoid
    
  • 不要對(duì)全局只讀對(duì)象重新賦值。

    eslint:no-global-assign

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

    eslint:no-implied-eval

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

    eslint:no-inner-declarations

    if (authenticated) {
      function setAuthUser () {}    // ? avoid
    }
    
  • 不要向 RegExp 構(gòu)造器傳入非法的正則表達(dá)式

    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
    
  • 外部變量不要與對(duì)象屬性重名。

    eslint: no-label-var

    var score = 100
    function game () {
      score: while (true) {      // ? avoid
        score -= 10
        if (score > 0) continue score
        break
      }
    }
    
  • 不要使用標(biāo)簽語句

    eslint: no-labels

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

    eslint:no-lone-blocks

    function myFunc () {
      {                   // ? avoid
        myOtherFunc()
      }
    }
    
    function myFunc () {
      myOtherFunc()       // ? ok
    }
    
  • 不要混合使用空格與制表符作為縮進(jìn)

    eslint:no-mixed-spaces-and-tabs

  • 除了縮進(jìn),不要使用多個(gè)空格。

    eslint:no-multi-spaces

    const id =    1234    // ? avoid
    const id = 1234       // ? ok
    
  • 不要使用多行字符串。

    eslint: no-multi-str

    const message = 'Hello \
                       world'     // ? avoid
    
  • new 創(chuàng)建對(duì)象實(shí)例后需要賦值給變量。

    eslint: no-new

    new Character()                     // ? avoid
    const character = new Character()   // ? ok
    
  • 禁止使用 Function 構(gòu)造器。

    eslint: no-new-func

    var sum = new Function('a', 'b', 'return a + b')    // ? avoid
    
  • 禁止使用 Object 構(gòu)造器

    eslint:no-new-object

    let config = new Object()   // ? avoid
    
  • 禁止使用 new require。

    eslint:no-new-require

    const myModule = new require('my-module')    // ? avoid
    
  • 禁止使用 Symbol 構(gòu)造器。

    eslint:no-new-symbol

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

    eslint:no-new-wrappers

    const message = new String('hello')   // ? avoid
    
  • 不要將全局對(duì)象的屬性作為函數(shù)調(diào)用。

    eslint: no-obj-calls

    const math = Math()   // ? avoid
    
  • 不要使用八進(jìn)制字面量。

    eslint: no-octal

    const octal = 042         // ? avoid
    const decimal = 34        // ? ok
    const octalString = '042' // ? ok
    
  • 字符串字面量中也不要使用八進(jìn)制轉(zhuǎn)義字符

    eslint:no-octal-escape

    const copyright = 'Copyright \251'  // ? avoid
    
  • 使用 __dirname__filename 時(shí)盡量避免使用字符串拼接。

    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
    
  • 不要重復(fù)聲明變量。

    eslint: no-redeclare

    let name = 'John'
    let name = 'Jane'     // ? avoid
    
    let name = 'John'
    name = 'Jane'         // ? ok
    
  • 正則中避免使用多個(gè)空格。

    eslint:no-regex-spaces

    const regexp = /test   value/   // ? avoid
    
    const regexp = /test {3}value/  // ? ok
    const regexp = /test value/     // ? ok
    
  • return 語句中的賦值必需有括號(hào)包裹。

    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
    
  • 避免將變量與自己進(jìn)行比較操作

    esint:no-self-compare

    if (score === score) {}   // ? avoid
    
  • 避免使用逗號(hào)操作符。

    eslint: no-sequences

    if (doSomething(), !!test) {}   // ? avoid
    
  • 不要隨意更改關(guān)鍵字的值

    eslint:no-shadow-restricted-names

    let undefined = 'value'     // ? avoid
    
  • 禁止使用稀疏數(shù)組(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 前請(qǐng)確保 super() 已調(diào)用。

    eslint:no-this-before-super

    class Dog extends Animal {
      constructor () {
        this.legs = 4     // ? avoid
        super()
      }
    }
    
  • throw 拋錯(cuò)時(shí),拋出 Error 對(duì)象而不是字符串。

    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
    
  • 循環(huán)語句中注意更新循環(huán)變量。

    eslint:no-unmodified-loop-condition

    for (let i = 0; i < items.length; j++) {...}    // ? avoid
    for (let i = 0; i < items.length; i++) {...}    // ? ok
    
  • 如果有更好的實(shí)現(xiàn),盡量不要使用三元表達(dá)式。

    eslint:no-unneeded-ternary

    let score = val ? val : 0     // ? avoid
    let score = val || 0          // ? ok
    
  • returnthrow,continuebreak 后不要再跟代碼。

    eslint:no-unreachable

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

    eslint:no-unsafe-finally

    try {
      // ...
    } catch (e) {
      // ...
    } finally {
      return 42     // ? avoid
    }
    
  • 關(guān)系運(yùn)算符的左值不要做取反操作。

    eslint:no-unsafe-negation

    if (!key in obj) {}       // ? avoid
    
  • 避免不必要的 .call().apply()。

    eslint:no-useless-call

    sum.call(null, 1, 2, 3)   // ? avoid
    
  • 避免使用不必要的計(jì)算值作對(duì)象屬性

    eslint:no-useless-computed-key

    const user = { ['name']: 'John Doe' }   // ? avoid
    const user = { name: 'John Doe' }       // ? ok
    
  • 禁止多余的構(gòu)造器

    eslint:no-useless-constructor

    class Car {
      constructor () {      // ? avoid
      }
    }
    
  • 禁止不必要的轉(zhuǎn)義。

    eslint:no-useless-escape

    let message = 'Hell\o'  // ? avoid
    
  • import, export 和解構(gòu)操作中,禁止賦值到同名變量。

    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
    
  • 對(duì)象屬性換行時(shí)注意統(tǒng)一代碼風(fēng)格。

    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
    }
    
  • 展開運(yùn)算符與它的表達(dá)式間不要留空白

    eslint:rest-spread-spacing

    fn(... args)    // ? avoid
    fn(...args)     // ? ok
    
  • 遇到分號(hào)時(shí)空格要后留前不留。

    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
    
  • 圓括號(hào)間不留空格

    eslint:space-in-parens

    getName( name )     // ? avoid
    getName(name)       // ? ok
    
  • 一元運(yùn)算符后面跟一個(gè)空格。

    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 的正確姿勢(shì)是使用 isNaN()。

    eslint: use-isnan

    if (price === NaN) { }      // ? avoid
    if (isNaN(price)) { }       // ? ok
    
  • 用合法的字符串跟 typeof 進(jìn)行比較操作

    eslint: valid-typeof

    typeof name === 'undefimed'     // ? avoid
    typeof name === 'undefined'     // ? ok
    
  • 自調(diào)用匿名函數(shù) (IIFEs) 使用括號(hào)包裹。

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

    eslint: yoda

    if (42 === age) { }    // ? avoid
    if (age === 42) { }    // ? ok
    

關(guān)于分號(hào)

  • 不要使用分號(hào)。(參見:1,23)

    eslint: semi

    window.alert('hi')   // ? ok
    window.alert('hi');  // ? avoid
    
  • 不要使用 (, [,or ` 等作為一行的開始。 在沒有分號(hào)的情況下代碼壓縮后會(huì)導(dǎo)致報(bào)錯(cuò),而堅(jiān)持這一規(guī)范則可避免出錯(cuò)。

    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)
    

拓展閱讀

一個(gè)值得觀看的視頻:
  • JavaScript 中的分號(hào)多余嗎?- YouTube

    當(dāng)前主流的代碼壓縮方案都是基于詞法(AST-based)進(jìn)行的,所以在處理無分號(hào)的代碼時(shí)完全沒有壓力(何況JavaScript 中分號(hào)本來就不是強(qiáng)制的)。

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

[自動(dòng)化插入分號(hào)的做法]是安全可依賴的,而且其產(chǎn)出的代碼能夠在所有瀏覽器里很好地運(yùn)行。Closure compiler, yuicompressor, packer 還有 jsmin 都能正確地對(duì)這樣的代碼進(jìn)行壓縮處理。并沒有任何性能相關(guān)的問題。

不得不說,Javascript 社區(qū)里的大牛們一直是錯(cuò)誤的,并不能教給你最佳實(shí)踐。真是讓人憂傷啊。

我建議先弄清楚 JS是怎樣斷句的(還有就是哪些地方看起來斷了其實(shí)并沒有),明白了這個(gè)后就可以隨心寫出漂亮的代碼了。

一般來說, \n 表示語句結(jié)束,除非:

  1. 該語句有未閉合的括號(hào),數(shù)組字面量, 對(duì)象字面量 或者其他不能正常結(jié)束一條語句的情況(譬如,以 ., 結(jié)尾)
  2. 該語句是 -- 或者 ++,它會(huì)將后面的內(nèi)容進(jìn)行自增或減)
  3. 該語句是 for()while(),doif() 或者 else 并且沒有 {
  4. 下一行以 [(,+,*,/,-,,,. 或者其他只會(huì)單獨(dú)出現(xiàn)在兩塊內(nèi)容間的二元操作符。

第一條很容易理解。即使在 JSLint 中,也允許JSON,構(gòu)造器的括號(hào)中,以及使用 var 配合 ,,結(jié)尾來聲明多個(gè)變量等這些情中包含 \n。

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

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

; 是條合法的 JavaScript 語句。所以 if(x); 等價(jià)于 if(x){},表示"如果 x 為真,什么也不做。",這種寫法在循環(huán)里面可以看到,就是當(dāng)條件判斷與條件更新是同一個(gè)方法的時(shí)候。
不常見,但也不至于沒聽說過吧。

第四條就是常見的 "看,說過要加分號(hào)!" 的情形。但這些情況可以通過在語句前面加上分號(hào)來解決,如果你確定該語句跟前面的沒關(guān)系的話。舉個(gè)例子,假如你想這樣:

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

那么完全可以這樣來寫:

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

后者的好處是分號(hào)比較矚目,一旦習(xí)慣后便再也不會(huì)看到以 ([ 開頭又不帶分號(hào)的語句了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • eslint配置方式 注釋配置:使用js注釋來直接嵌入ESLint配置信息到一個(gè)文件里 配置文件:使用一個(gè)js文件...
    輕輕地走在路上閱讀 1,567評(píng)論 0 0
  • 前言 在使用vue-cli初始化項(xiàng)目時(shí),會(huì)有一個(gè)ESLint選項(xiàng),即代碼規(guī)范和錯(cuò)誤檢查工具。默認(rèn)提供兩種檢查規(guī)范:...
    迦葉凡閱讀 2,414評(píng)論 0 1
  • 1.extends屬性 一個(gè)配置文件可以被基礎(chǔ)配置中的已啟用的規(guī)則繼承??梢允褂靡韵乱?guī)則繼承: (1)'eslin...
    阿bai君閱讀 1,613評(píng)論 0 1
  • 縮進(jìn) 使用兩個(gè)空格進(jìn)行縮進(jìn)。eslint: indent[http://eslint.org/docs/rules...
    誰家智障閱讀 618評(píng)論 0 0
  • JavaScript 編碼規(guī)范(草案) 該規(guī)范改編自 Airbnb JavaScript Style Guide[...
    暖lily閱讀 585評(píng)論 0 0

友情鏈接更多精彩內(nèi)容