代碼質量工具從 JSLint 演進至 ESLink,已成現代前端工程標配。本文對比兩者歷史與現狀,詳細講解 ESLint 規則配置、共享配置、Prettier 整合、Git Hooks、CI/CD 流水線接入、VS Code/WebStorm/IDE 實時提示,助力團隊統一代碼風格、捕獲潛在 Bug。
++、要求單引號),難以定製,已基本退出主流。.eslintrc.jsmodule.exports = {
env: { browser: true, es2022: true, node: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:vue/vue3-recommended',
'prettier' // 關閉與 Prettier 衝突的規則
],
parser: '@typescript-eslint/parser',
parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
plugins: ['@typescript-eslint', 'vue', 'prettier'],
rules: {
'prettier/prettier': 'error',
'no-console': ['warn', { allow: ['warn', 'error'] }],
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
'vue/multi-word-component-names': 'off'
},
overrides: [
{ files: ['*.test.ts', '*.spec.ts'], env: { jest: true } }
]
};
// .prettierrc
{ "semi": true, "singleQuote": true, "tabWidth": 2, "trailingComma": "es5", "printWidth": 100 }
// package.json scripts
"lint": "eslint . --ext .js,.ts,.vue",
"lint:fix": "npm run lint -- --fix",
"format": "prettier --write ."
# 安裝 husky + lint-staged
npx husky install
npx husky add .husky/pre-commit "npx lint-staged"
# package.json
"lint-staged": {
"*.{js,ts,vue}": ["eslint --fix", "prettier --write"]
}
# GitHub Actions .github/workflows/lint.yml
name: Lint
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 20, cache: 'npm' }
- run: npm ci
- run: npm run lint
"eslint.validate": ["javascript", "typescript", "vue"]、"editor.codeActionsOnSave": { "source.fixAll.eslint": "explicit" }。| 規則 | 建議 | 說明 |
|---|---|---|
no-unused-vars | error | 捕獲死代碼 |
no-undef | error | 防止拼寫錯誤 |
eqeqeq | error | 強制 === |
curly | error | 強制大括號 |
default-case | warn | switch 兜底 |
prefer-const | error | 優先 const |