跳轉到內容

ESLint + Prettier 代碼規範最佳實踐 2026

ESLint + Prettier 代碼規範

💡 為什麼需要代碼規範? 好的代碼規範能提升代碼可讀性、減少 Bug、降低維護成本、統一團隊協作風格。ESLint 負責代碼質量檢查,Prettier 負責代碼格式化,兩者結合是現代前端項目的標配。

本文將帶你從零搭建完整的代碼規範體系:

  • ✅ ESLint 與 Prettier 核心概念
  • ✅ 從零開始配置 ESLint
  • ✅ Prettier 格式化配置
  • ✅ TypeScript / Vue / React 集成
  • ✅ 常用規則集推薦
  • ✅ Git 提交自動檢查(Husky + lint-staged)
  • ✅ CI/CD 集成
  • ✅ 常見問題與解決方案

一、基礎概念

1.1 ESLint 是什麼

ESLint 是一個可組裝的 JavaScript 和 JSX 檢查工具,用於發現代碼中的問題並統一代碼風格。

ESLint 的主要能力:

  • 🔍 代碼檢查:發現潛在 Bug 和錯誤
  • 📏 代碼規範:統一團隊代碼風格
  • 🔧 自動修復:一鍵修復大部分問題
  • 🧩 高度可配置:按需定製規則

1.2 Prettier 是什麼

Prettier 是一個「有態度」的代碼格式化工具,支持多種語言,完全接管代碼格式。

Prettier 的主要特點:

  • 開箱即用:幾乎零配置即可使用
  • 🔄 多語言支持:JS/TS/JSX/JSON/CSS/HTML/Markdown 等
  • 🤝 徹底統一:消除所有格式爭議
  • 快速高效:秒級格式化整個項目

1.3 為什麼兩者結合使用

工具擅長不擅長
ESLint代碼質量、語法錯誤、最佳實踐格式化(慢且不徹底)
Prettier代碼格式化、風格統一代碼質量檢查

最佳實踐: ESLint 管質量,Prettier 管格式,各司其職,完美配合。


二、快速開始

2.1 環境要求

  • Node.js: 18+ (推薦 LTS)
  • 包管理器: npm / yarn / pnpm
  • 編輯器: VS Code(推薦)

2.2 基礎項目配置

1. 安裝依賴

bash
npm install -D eslint prettier eslint-config-prettier eslint-plugin-prettier
bash
pnpm add -D eslint prettier eslint-config-prettier eslint-plugin-prettier
bash
yarn add -D eslint prettier eslint-config-prettier eslint-plugin-prettier

依賴說明:

  • eslint - ESLint 核心
  • prettier - Prettier 核心
  • eslint-config-prettier - 關閉 ESLint 中與 Prettier 衝突的格式規則
  • eslint-plugin-prettier - 讓 Prettier 規則作為 ESLint 規則運行

2. 創建 ESLint 配置

js
// .eslintrc.js
module.exports = {
  env: {
    browser: true,
    node: true,
    es2022: true
  },
  extends: [
    'eslint:recommended',
    'plugin:prettier/recommended'
  ],
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module'
  },
  rules: {}
}

3. 創建 Prettier 配置

js
// .prettierrc.js
module.exports = {
  // 每行最大字符數
  printWidth: 100,
  
  // 縮進空格數
  tabWidth: 2,
  
  // 使用製表符縮進
  useTabs: false,
  
  // 語句末尾加分號
  semi: false,
  
  // 使用單引號
  singleQuote: true,
  
  // 對象屬性的引號
  quoteProps: 'as-needed',
  
  // JSX 使用單引號
  jsxSingleQuote: false,
  
  // 尾隨逗號
  trailingComma: 'none',
  
  // 對象大括號內空格
  bracketSpacing: true,
  
  // 箭頭函數參數括號
  arrowParens: 'always',
  
  // 行結束符
  endOfLine: 'lf'
}

4. 創建忽略文件

// .eslintignore
node_modules
dist
build
public
*.min.js
// .prettierignore
node_modules
dist
build
public
*.min.js
*.min.css

5. 添加 npm scripts

json
{
  "scripts": {
    "lint": "eslint .",
    "lint:fix": "eslint . --fix",
    "format": "prettier --write .",
    "format:check": "prettier --check ."
  }
}

6. 運行檢查

bash
# 檢查代碼問題
npm run lint

# 自動修復
npm run lint:fix

# 格式化代碼
npm run format

# 檢查格式
npm run format:check

三、TypeScript 集成

3.1 安裝依賴

bash
npm install -D @typescript-eslint/parser @typescript-eslint/eslint-plugin typescript
bash
pnpm add -D @typescript-eslint/parser @typescript-eslint/eslint-plugin typescript

3.2 配置 ESLint

js
// .eslintrc.js
module.exports = {
  env: {
    browser: true,
    node: true,
    es2022: true
  },
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended'
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module'
  },
  plugins: ['@typescript-eslint'],
  rules: {
    // 禁止使用 any
    '@typescript-eslint/no-explicit-any': 'warn',
    
    // 要求函數返回類型
    '@typescript-eslint/explicit-function-return-type': 'off',
    
    // 禁止未使用的變量
    '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
    
    // 禁止使用 @ts-ignore
    '@typescript-eslint/ban-ts-comment': 'warn',
    
    // 類型導入
    '@typescript-eslint/consistent-type-imports': 'error'
  }
}

3.3 TypeScript 配置

json
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "skipLibCheck": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts"],
  "exclude": ["node_modules", "dist"]
}

四、Vue 3 集成

4.1 安裝依賴

bash
npm install -D eslint-plugin-vue vue-eslint-parser
bash
pnpm add -D eslint-plugin-vue vue-eslint-parser

4.2 配置 ESLint

js
// .eslintrc.js
module.exports = {
  env: {
    browser: true,
    node: true,
    es2022: true
  },
  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-recommended',
    'plugin:prettier/recommended'
  ],
  parser: 'vue-eslint-parser',
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
    parser: '@typescript-eslint/parser'
  },
  rules: {
    // 組件名稱多詞
    'vue/multi-word-component-names': 'off',
    
    // props 默認值
    'vue/require-default-prop': 'off',
    
    // v-for 必須有 key
    'vue/require-v-for-key': 'error',
    
    // 模板中使用單引號
    'vue/html-quotes': ['error', 'double'],
    
    // 自閉合標籤
    'vue/html-self-closing': [
      'error',
      {
        html: { void: 'always', normal: 'always', component: 'always' }
      }
    ],
    
    // 組件名大小寫
    'vue/component-name-in-template-casing': ['error', 'PascalCase']
  }
}

五、React 集成

5.1 安裝依賴

bash
npm install -D eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y
bash
pnpm add -D eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y

5.2 配置 ESLint

js
// .eslintrc.js
module.exports = {
  env: {
    browser: true,
    node: true,
    es2022: true
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:react-hooks/recommended',
    'plugin:jsx-a11y/recommended',
    'plugin:prettier/recommended'
  ],
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true
    }
  },
  settings: {
    react: {
      version: 'detect'
    }
  },
  rules: {
    // React 導入(新 JSX transform 不需要)
    'react/react-in-jsx-scope': 'off',
    
    // props 類型(TypeScript 項目可關閉)
    'react/prop-types': 'off',
    
    // hooks 依賴
    'react-hooks/exhaustive-deps': 'warn',
    
    // 按鈕類型
    'react/button-has-type': 'error',
    
    // 危險的 dangerouslySetInnerHTML
    'react/no-danger': 'warn'
  }
}

六、常用規則集推薦

6.1 流行規則集對比

規則集特點適用場景
eslint:recommendedESLint 官方推薦,基礎規則所有項目
standardJavaScript 標準風格喜歡無分號風格的團隊
airbnb最嚴格的規則集,覆蓋面廣追求高質量的大型團隊
googleGoogle 風格指南喜歡 Google 風格的團隊
xo嚴格但合理的規則集個人或小團隊

6.2 推薦配置組合

Vue 3 + TypeScript 項目:

js
extends: [
  'eslint:recommended',
  'plugin:@typescript-eslint/recommended',
  'plugin:vue/vue3-recommended',
  'plugin:prettier/recommended'
]

React + TypeScript 項目:

js
extends: [
  'eslint:recommended',
  'plugin:@typescript-eslint/recommended',
  'plugin:react/recommended',
  'plugin:react-hooks/recommended',
  'plugin:jsx-a11y/recommended',
  'plugin:prettier/recommended'
]

6.3 必開規則

js
rules: {
  // 禁止未使用的變量
  'no-unused-vars': 'warn',
  
  // 禁止未定義的變量
  'no-undef': 'error',
  
  // 禁止使用 console(可根據情況調整)
  'no-console': ['warn', { allow: ['warn', 'error'] }],
  
  // 禁止使用 debugger
  'no-debugger': 'error',
  
  // 禁止重複的 case 標籤
  'no-duplicate-case': 'error',
  
  // 禁止空的代碼塊
  'no-empty': 'warn',
  
  // 強制使用 ===
  'eqeqeq': ['error', 'always'],
  
  // 禁止 var
  'no-var': 'error',
  
  // 優先使用 const
  'prefer-const': 'error',
  
  // 禁止修改函數參數
  'no-param-reassign': 'error'
}

七、VS Code 集成

7.1 安裝插件

在 VS Code 中安裝以下插件:

  1. ESLint - 代碼檢查
  2. Prettier - Code formatter - 代碼格式化

7.2 配置 VS Code

json
// .vscode/settings.json
{
  // 默認格式化工具
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  
  // 保存時格式化
  "editor.formatOnSave": true,
  
  // 保存時自動修復 ESLint 問題
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  },
  
  // 顯示 ESLint 輸出通道
  "eslint.debug": false,
  
  // 啟用 ESLint
  "eslint.enable": true,
  
  // Prettier 配置文件路徑
  "prettier.configPath": ".prettierrc.js",
  
  // 需要 Prettier 的語言
  "prettier.documentSelectors": [
    "**/*.js",
    "**/*.jsx",
    "**/*.ts",
    "**/*.tsx",
    "**/*.vue",
    "**/*.json",
    "**/*.css",
    "**/*.scss",
    "**/*.md"
  ],
  
  // 每行長度參考線
  "editor.rulers": [100]
}

7.3 推薦的擴展推薦

json
// .vscode/extensions.json
{
  "recommendations": [
    "dbaeumer.vscode-eslint",
    "esbenp.prettier-vscode",
    "editorconfig.editorconfig"
  ]
}

八、Git 提交檢查

8.1 使用 Husky + lint-staged

1. 安裝依賴

bash
npm install -D husky lint-staged
bash
pnpm add -D husky lint-staged

2. 啟用 Git Hooks

bash
npx husky install

3. 添加 prepare 腳本

json
{
  "scripts": {
    "prepare": "husky install"
  }
}

4. 創建 pre-commit hook

bash
npx husky add .husky/pre-commit "npx lint-staged"

5. 配置 lint-staged

json
// package.json
{
  "lint-staged": {
    "*.{js,jsx,ts,tsx,vue}": [
      "eslint --fix",
      "prettier --write"
    ],
    "*.{json,css,scss,md,html}": [
      "prettier --write"
    ]
  }
}

8.2 提交信息規範

安裝 commitlint:

bash
npm install -D @commitlint/cli @commitlint/config-conventional

配置 commitlint:

js
// commitlint.config.js
module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [
      2,
      'always',
      [
        'feat',
        'fix',
        'docs',
        'style',
        'refactor',
        'perf',
        'test',
        'chore',
        'revert',
        'build',
        'ci'
      ]
    ],
    'subject-case': [0],
    'subject-full-stop': [0],
    'header-max-length': [2, 'always', 100]
  }
}

創建 commit-msg hook:

bash
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'

九、CI/CD 集成

9.1 GitHub Actions

yaml
# .github/workflows/lint.yml
name: Lint
on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main, develop]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'
          
      - name: Install dependencies
        run: npm ci
        
      - name: Run ESLint
        run: npm run lint
        
      - name: Check Prettier format
        run: npm run format:check

9.2 GitLab CI

yaml
# .gitlab-ci.yml
lint:
  stage: test
  image: node:20
  cache:
    paths:
      - node_modules/
  script:
    - npm ci
    - npm run lint
    - npm run format:check
  only:
    - merge_requests
    - main
    - develop

十、EditorConfig

EditorConfig 用於統一編輯器基礎配置,配合 Prettier 使用效果更佳。

ini
# .editorconfig
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 2

[*.md]
trim_trailing_whitespace = false

[Makefile]
indent_style = tab

十一、常見問題

11.1 ESLint 與 Prettier 衝突

現象: ESLint 報的錯被 Prettier 格式化後還是報錯。

解決方案:

  1. 確保安裝了 eslint-config-prettier
  2. extends 中把 plugin:prettier/recommended 放在最後
  3. 不要在 ESLint 中配置格式相關的規則

11.2 保存時不自動格式化

檢查項:

  1. 是否安裝了 Prettier 插件
  2. editor.formatOnSave 是否開啟
  3. editor.defaultFormatter 是否設置正確
  4. 項目根目錄是否有 Prettier 配置文件

11.3 部分文件不想檢查

.eslintignore.prettierignore 中添加:

node_modules
dist
build
*.min.js
public

也可以在文件頂部用註釋禁用:

js
/* eslint-disable */
// 這段代碼不檢查
js
/* eslint-disable no-console */
// 只禁用某個規則
console.log('hello')

11.4 舊項目引入 lint 報錯太多

解決方案:

  1. 先用 eslint --fix 自動修復能修的
  2. 把嚴重錯誤降為 warning,逐步整改
  3. 只對新文件嚴格檢查,老文件逐步遷移
  4. 使用 eslint-nibble 逐步修復
bash
# 只檢查暫存的文件(推薦)
npx lint-staged

十二、配置速查

12.1 完整 Vue 3 + TS 配置

js
// .eslintrc.js
module.exports = {
  root: true,
  env: {
    browser: true,
    node: true,
    es2022: true
  },
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:vue/vue3-recommended',
    'plugin:prettier/recommended'
  ],
  parser: 'vue-eslint-parser',
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
    parser: '@typescript-eslint/parser'
  },
  rules: {
    'vue/multi-word-component-names': 'off',
    '@typescript-eslint/no-explicit-any': 'warn',
    '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
    'no-console': ['warn', { allow: ['warn', 'error'] }],
    'prefer-const': 'error',
    'eqeqeq': ['error', 'always']
  }
}

12.2 Prettier 常用配置速查

js
module.exports = {
  printWidth: 100,       // 行寬
  tabWidth: 2,           // 縮進
  useTabs: false,        // 用空格不用 tab
  semi: false,           // 無分號
  singleQuote: true,     // 單引號
  trailingComma: 'none', // 無尾隨逗號
  bracketSpacing: true,  // 大括號內空格
  arrowParens: 'always', // 箭頭函數參數括號
  endOfLine: 'lf'        // 換行符
}

12.3 常用命令速查

bash
# 檢查所有文件
eslint .

# 自動修復
eslint . --fix

# 檢查指定目錄
eslint src/

# 忽略某些文件
eslint . --ignore-pattern "*.test.js"

# 格式化所有文件
prettier --write .

# 檢查格式
prettier --check .

# 格式化指定文件
prettier --write src/**/*.js

相關文章推薦:

🎯 代碼規範不是約束,而是提升團隊協作效率和代碼質量的利器。越早建立規範,後期維護成本越低。從今天開始,讓你的代碼更優雅!

最後更新於: