Skip to content

JavaScript 主流 Coding Style 規範比較

tags: 規範 JavaScript

Standard JS ( JavaScript Standard Style )

不用使用設定檔,引入就可以使用。並且「不使用分號」
https://standardjs.com/readme-zhtw.html

Google JavaScript Style Guide

注重長期維護性與 JSDoc 註解,Google 內部專案標準
https://google.github.io/styleguide/jsguide.html

Airbnb JavaScript Style Guide

規則最詳盡、嚴謹,是目前現代 Web 開發(特別是 React)的業界標準 https://javascript.airbnb.tech/

三者綜合比較

專案特性與適用性

特性JavaScript Standard StyleGoogle JavaScript Style GuideAirbnb JavaScript Style Guide
配置複雜度零配置 (無法修改規則)中等高 (可透過 ESLint 高度客製)
嚴格程度最寬鬆 (但在格式上強制)中等嚴格最嚴格 (規則數量最多)
主要客群個人開發者、小型專案、開源套件Google 內部、Angular 開發者React 開發者、大型企業團隊
社群現況社群驅動,擁護者眾多逐漸轉向推廣 TypeScript 規範目前業界主流,最多人使用

語法規則細節

規則JavaScript Standard StyleGoogle JavaScript Style GuideAirbnb JavaScript Style Guide
分號 (;)不使用必須使用必須使用
縮排2 個空格2 個空格2 個空格
字串引號優先單引號 '優先單引號 '優先單引號 '
函式後空格有空格 fn ()無空格 fn()無空格 fn()
箭頭函式單參數省略括號單參數省略括號參數一律加上括號 (x) =>
結尾逗號禁止使用多行時允許多行時強制使用 (Dangling comma)
物件大括號必須使用必須使用必須使用
運算符換行運算符在新行開頭運算符在前行結尾運算符在新行開頭
命名規範駝峰式 (camelCase)駝峰式 (私有變數結尾加 _)駝峰式 (常數全大寫 CONST_VAR)

程式碼範例對照

分號使用

javascript
// Standard Style (No Semicolon)
let name = 'John'
function greet () {
  console.log('Hello')
}

// Google / Airbnb Style (With Semicolon)
let name = 'John';
function greet() {
  console.log('Hello');
}

縮排 (Tabs / Indent)

三者均達成共識:使用 2 個空格。

javascript
function example() {
  if (true) {
    console.log('Indented with 2 spaces')
  }
}

引號(Quotes)

javascript
// Standard / Google / Airbnb (優先使用 Single Quote)
let str = 'Hello'
let template = `Value: ${str}`

函式與括號空格 (Space before function paren)

這是 Standard Style 最具辨識度的差異

javascript
// Standard Style (名稱與括號間有空格)
function calculateTotal () { ... }

// Google / Airbnb Style (無空格)
function calculateTotal() { ... }

箭頭函式 (Arrow Functions)

javascript
// Standard / Google Style (單參數可省略括號)
const add = x => x + 1
const multiply = (x, y) => x * y

// Airbnb Style (現代規範:無論幾個參數一律加括號)
const add = (x) => x + 1
const multiply = (x, y) => x * y

保留關鍵字/運算符換行 (Operator Line Break)

javascript
// Standard / Airbnb Style (運算符在新行開始)
const result = someVeryLongFunctionName()
  + anotherLongVariable

// Google Style (運算符在當前行結尾)
const result = someVeryLongFunctionName() +
    anotherLongVariable

結尾逗號 (Trailing Commas)

javascript
// Standard Style (No Trailing Comma)
const arr = [1, 2, 3]
const obj = {
  a: 1,
  b: 2
}

// Google / Airbnb Style (多行時必須/建議加上逗號)
const arr = [1, 2, 3,]
const obj = {
  a: 1,
  b: 2,
}

命名規範 (Naming Convention)

javascript
// Standard Style (Pure Camel Case)
let userName = 'John'
function calculateTotal() {}

// Google Style (Private with Underscore)
let _privateVar = 'secret'
function _privateMethod() {}

// Airbnb Style (Constants UPPER_CASE)
const MAX_COUNT = 100
let userName = 'John'

參考文件