引言
作為前端開發者,你是否遇到過這樣的情況:團隊成員寫出的代碼風格各異,有人喜歡用分號,有人不用;有人用雙引號,有人用單引號;代碼評審時總是在糾結這些格式問題而不是業務邏輯?或者在大型項目中,因為一個未定義的變量導致生產環境報錯?
ESLint 就是為了解決這些問題而生的。它不僅能統一代碼風格,更重要的是能在開發階段就發現潛在的錯誤,提高代碼質量和開發效率。
本文將從零開始,帶你全面掌握 ESLint 的使用,從基礎配置到高級定制,從個人項目到團隊協作,讓你成為 ESLint 的專家。
什么是ESLint?
定義與作用
ESLint 是一個開源的 JavaScript 代碼靜態分析工具,由 Nicholas C. Zakas 在 2013 年創建。它的主要作用是:
- 代碼質量檢查:識別有問題的模式或不符合特定規則的代碼
- 代碼風格統一:強制執行一致的代碼風格
- 錯誤預防:在運行前捕獲潛在的錯誤
- 最佳實踐提醒:推廣 JavaScript 最佳實踐
核心特性
- 完全可配置:所有規則都可以開啟/關閉,每個規則都有多個設置選項
- 插件化架構:可以通過插件擴展功能,支持 TypeScript、React、Vue 等
- 支持多種配置格式:JSON、YAML、JavaScript 等
- IDE 集成:主流編輯器都有相應插件
- 自動修復:大部分格式問題可以自動修復
安裝與基礎配置
安裝ESLint
# 全局安裝(不推薦)
npm install -g eslint# 項目內安裝(推薦)
npm install --save-dev eslint# 使用 yarn
yarn add --dev eslint# 使用 pnpm
pnpm add -D eslint
初始化配置
# 交互式創建配置文件
npx eslint --init# 或者使用
npm init @eslint/config
執行命令后,ESLint 會問你幾個問題:
-
How would you like to use ESLint?
- To check syntax only(僅檢查語法)
- To check syntax and find problems(檢查語法并發現問題)
- To check syntax, find problems, and enforce code style(檢查語法、發現問題并強制代碼風格)
-
What type of modules does your project use?
- JavaScript modules (import/export)
- CommonJS (require/exports)
- None of these
-
Which framework does your project use?
- React
- Vue.js
- None of these
-
Does your project use TypeScript? Yes/No
-
Where does your code run?
- Browser
- Node
-
What format do you want your config file to be in?
- JavaScript
- YAML
- JSON
基礎配置文件示例
根據你的選擇,ESLint 會生成對應的配置文件。以 .eslintrc.js
為例:
module.exports = {// 環境定義env: {browser: true,es2021: true,node: true},// 繼承的配置extends: ['eslint:recommended'],// 解析器選項parserOptions: {ecmaVersion: 12,sourceType: 'module'},// 自定義規則rules: {// 在這里添加或覆蓋規則}
};
配置文件詳解
配置文件類型與優先級
ESLint 支持多種配置文件格式,優先級從高到低:
.eslintrc.js
.eslintrc.cjs
.eslintrc.yaml
或.eslintrc.yml
.eslintrc.json
package.json
中的eslintConfig
字段
核心配置選項
1. env(環境配置)
定義代碼運行的環境,影響全局變量的可用性:
module.exports = {env: {browser: true, // 瀏覽器全局變量node: true, // Node.js 全局變量es2021: true, // ES2021 語法支持jest: true, // Jest 測試環境jquery: true, // jQuery 全局變量worker: true, // Web Workerserviceworker: true // Service Worker}
};
2. extends(擴展配置)
繼承其他的配置文件或預設規則集:
module.exports = {extends: ['eslint:recommended', // ESLint 推薦規則'@typescript-eslint/recommended', // TypeScript 推薦規則'plugin:react/recommended', // React 推薦規則'plugin:vue/essential', // Vue 基礎規則'airbnb', // Airbnb 風格指南'prettier' // Prettier 兼容]
};
3. parser(解析器)
指定 ESLint 使用的解析器:
module.exports = {// TypeScript 解析器parser: '@typescript-eslint/parser',// Babel 解析器// parser: '@babel/eslint-parser',parserOptions: {ecmaVersion: 2021,sourceType: 'module',ecmaFeatures: {jsx: true, // 支持 JSXglobalReturn: true, // 允許全局 returnimpliedStrict: true // 啟用嚴格模式}}
};
4. plugins(插件)
擴展 ESLint 功能的插件:
module.exports = {plugins: ['@typescript-eslint', // TypeScript 插件'react', // React 插件'react-hooks', // React Hooks 插件'import', // import/export 插件'jsx-a11y', // 無障礙訪問插件'prettier' // Prettier 插件]
};
5. rules(規則配置)
這是 ESLint 的核心,定義具體的檢查規則:
module.exports = {rules: {// 錯誤級別: "off" 或 0, "warn" 或 1, "error" 或 2// 代碼質量相關'no-unused-vars': 'error', // 禁止未使用的變量'no-undef': 'error', // 禁止使用未定義的變量'no-console': 'warn', // 警告使用 console'no-debugger': 'error', // 禁止使用 debugger// 代碼風格相關'indent': ['error', 2], // 強制縮進為 2 個空格'quotes': ['error', 'single'], // 強制使用單引號'semi': ['error', 'always'], // 強制使用分號'comma-dangle': ['error', 'never'], // 禁止末尾逗號// ES6+ 相關'prefer-const': 'error', // 優先使用 const'arrow-spacing': 'error', // 箭頭函數空格'template-curly-spacing': 'error', // 模板字符串空格// 函數相關'func-style': ['error', 'declaration'], // 函數聲明風格'max-params': ['error', 4], // 最多 4 個參數// 對象和數組'object-curly-spacing': ['error', 'always'], // 對象花括號空格'array-bracket-spacing': ['error', 'never'], // 數組方括號空格}
};
高級配置選項
1. globals(全局變量)
定義額外的全局變量:
module.exports = {globals: {myCustomGlobal: 'readonly', // 只讀anotherGlobal: 'writable', // 可寫$: 'readonly', // jQuery_: 'readonly' // Lodash}
};
2. overrides(覆蓋配置)
為特定文件或目錄設置不同的規則:
module.exports = {rules: {// 全局規則'no-console': 'error'},overrides: [{// 對測試文件的特殊配置files: ['**/*.test.js', '**/*.spec.js'],env: {jest: true},rules: {'no-console': 'off' // 測試文件允許使用 console}},{// 對 TypeScript 文件的配置files: ['**/*.ts', '**/*.tsx'],parser: '@typescript-eslint/parser',plugins: ['@typescript-eslint'],rules: {'@typescript-eslint/no-unused-vars': 'error'}}]
};
3. ignorePatterns(忽略模式)
指定要忽略的文件和目錄:
module.exports = {ignorePatterns: ['dist/','build/','node_modules/','*.min.js','coverage/']
};
常用規則詳解
代碼質量規則
1. 變量相關
{// 禁止使用未聲明的變量'no-undef': 'error',// 禁止未使用的變量'no-unused-vars': ['error', {vars: 'all', // 檢查所有變量args: 'after-used', // 檢查使用后的參數ignoreRestSiblings: true // 忽略剩余兄弟元素}],// 禁止重復聲明變量'no-redeclare': 'error',// 禁止在變量定義之前使用'no-use-before-define': ['error', {functions: false, // 函數聲明提升classes: true,variables: true}]
}
2. 函數相關
{// 要求或禁止使用命名的 function 表達式'func-names': ['error', 'as-needed'],// 強制函數最大行數'max-lines-per-function': ['error', {max: 50,skipBlankLines: true,skipComments: true}],// 限制函數參數數量'max-params': ['error', 4],// 禁止使用 arguments.caller 或 arguments.callee'no-caller': 'error'
}
3. 對象和數組
{// 禁止對象字面量中出現重復的 key'no-dupe-keys': 'error',// 禁止數組中出現重復的元素'no-dupe-args': 'error',// 強制對象字面量屬性名稱使用一致的引號'quote-props': ['error', 'as-needed'],// 要求對象字面量簡寫語法'object-shorthand': ['error', 'always']
}
代碼風格規則
1. 空格和縮進
{// 強制使用一致的縮進'indent': ['error', 2, {SwitchCase: 1, // switch 語句縮進VariableDeclarator: 1, // 變量聲明縮進outerIIFEBody: 1 // IIFE 縮進}],// 強制在逗號前后使用一致的空格'comma-spacing': ['error', {before: false,after: true}],// 強制在對象字面量的屬性中鍵和值之間使用一致的間距'key-spacing': ['error', {beforeColon: false,afterColon: true}]
}
2. 引號和分號
{// 強制使用一致的引號'quotes': ['error', 'single', {avoidEscape: true, // 避免轉義allowTemplateLiterals: true // 允許模板字符串}],// 要求或禁止使用分號'semi': ['error', 'always'],// 強制分號之前和之后使用一致的空格'semi-spacing': ['error', {before: false,after: true}]
}
ES6+ 規則
{// 要求使用 const 聲明那些聲明后不再被修改的變量'prefer-const': 'error',// 要求使用箭頭函數作為回調'prefer-arrow-callback': 'error',// 要求使用模板字面量而非字符串連接'prefer-template': 'error',// 強制箭頭函數的箭頭前后使用一致的空格'arrow-spacing': ['error', {before: true,after: true}],// 要求解構賦值'prefer-destructuring': ['error', {array: true,object: true}]
}
實際項目配置示例
React項目配置
module.exports = {env: {browser: true,es2021: true,node: true},extends: ['eslint:recommended','plugin:react/recommended','plugin:react-hooks/recommended','plugin:jsx-a11y/recommended'],parser: '@babel/eslint-parser',parserOptions: {ecmaFeatures: {jsx: true},ecmaVersion: 12,sourceType: 'module',requireConfigFile: false,babelOptions: {presets: ['@babel/preset-react']}},plugins: ['react','react-hooks','jsx-a11y'],rules: {// React 相關'react/prop-types': 'error','react/jsx-uses-react': 'off','react/react-in-jsx-scope': 'off','react/jsx-filename-extension': [1, { extensions: ['.js', '.jsx'] }],// React Hooks'react-hooks/rules-of-hooks': 'error','react-hooks/exhaustive-deps': 'warn',// JSX 相關'jsx-quotes': ['error', 'prefer-double'],'react/jsx-indent': ['error', 2],'react/jsx-indent-props': ['error', 2]},settings: {react: {version: 'detect'}}
};
TypeScript項目配置
module.exports = {env: {browser: true,es2021: true,node: true},extends: ['eslint:recommended','@typescript-eslint/recommended','@typescript-eslint/recommended-requiring-type-checking'],parser: '@typescript-eslint/parser',parserOptions: {ecmaVersion: 12,sourceType: 'module',project: './tsconfig.json'},plugins: ['@typescript-eslint'],rules: {// TypeScript 特定規則'@typescript-eslint/no-unused-vars': 'error','@typescript-eslint/no-explicit-any': 'warn','@typescript-eslint/explicit-function-return-type': 'off','@typescript-eslint/explicit-module-boundary-types': 'off','@typescript-eslint/no-non-null-assertion': 'warn',// 類型檢查'@typescript-eslint/strict-boolean-expressions': 'error','@typescript-eslint/prefer-nullish-coalescing': 'error','@typescript-eslint/prefer-optional-chain': 'error',// 命名約定'@typescript-eslint/naming-convention': ['error',{selector: 'interface',format: ['PascalCase'],prefix: ['I']},{selector: 'typeAlias',format: ['PascalCase']},{selector: 'enum',format: ['PascalCase']}]}
};
Node.js項目配置
module.exports = {env: {node: true,es2021: true},extends: ['eslint:recommended'],parserOptions: {ecmaVersion: 12,sourceType: 'module'},rules: {// Node.js 特定規則'no-process-exit': 'error','no-process-env': 'off','global-require': 'error',// 回調函數'callback-return': 'error','handle-callback-err': 'error',// Buffer 相關'no-buffer-constructor': 'error',// 路徑相關'no-path-concat': 'error',// 同步方法'no-sync': 'warn'}
};
命令行使用
基本命令
# 檢查單個文件
npx eslint file.js# 檢查多個文件
npx eslint file1.js file2.js# 檢查目錄
npx eslint src/# 檢查特定擴展名的文件
npx eslint src/ --ext .js,.jsx,.ts,.tsx# 自動修復可修復的問題
npx eslint src/ --fix# 輸出格式化
npx eslint src/ --format table
npx eslint src/ --format json
高級命令選項
# 忽略 .eslintignore 文件
npx eslint src/ --no-ignore# 指定配置文件
npx eslint src/ --config .eslintrc.custom.js# 只運行特定規則
npx eslint src/ --rule 'quotes: error'# 禁用特定規則
npx eslint src/ --rule 'no-console: off'# 緩存結果以提高性能
npx eslint src/ --cache# 指定緩存位置
npx eslint src/ --cache --cache-location .eslintcache# 最大警告數
npx eslint src/ --max-warnings 0
package.json 腳本配置
{"scripts": {"lint": "eslint src/","lint:fix": "eslint src/ --fix","lint:check": "eslint src/ --max-warnings 0","lint:cache": "eslint src/ --cache","precommit": "lint-staged"},"lint-staged": {"*.{js,jsx,ts,tsx}": ["eslint --fix","git add"]}
}
IDE集成
VS Code集成
-
安裝ESLint插件
- 在擴展商店搜索 “ESLint”
- 安裝官方的 ESLint 插件
-
配置settings.json
{"eslint.enable": true,"eslint.autoFixOnSave": true,"eslint.validate": ["javascript","javascriptreact","typescript","typescriptreact"],"editor.codeActionsOnSave": {"source.fixAll.eslint": true},"eslint.workingDirectories": ["./src"]
}
WebStorm/IDEA集成
- 打開 Settings/Preferences
- 導航到 Languages & Frameworks > JavaScript > Code Quality Tools > ESLint
- 勾選 “Automatic ESLint configuration”
- 配置 “Run eslint --fix on save”
與其他工具集成
與Prettier集成
# 安裝相關包
npm install --save-dev prettier eslint-config-prettier eslint-plugin-prettier# .eslintrc.js 配置
module.exports = {extends: ['eslint:recommended','prettier' // 必須放在最后],plugins: ['prettier'],rules: {'prettier/prettier': 'error'}
};# .prettierrc 配置
{"semi": true,"trailingComma": "es5","singleQuote": true,"printWidth": 80,"tabWidth": 2
}
與Husky和lint-staged集成
# 安裝
npm install --save-dev husky lint-staged# package.json 配置
{"husky": {"hooks": {"pre-commit": "lint-staged"}},"lint-staged": {"*.{js,jsx,ts,tsx}": ["eslint --fix","prettier --write","git add"]}
}
與Webpack集成
// webpack.config.js
const ESLintPlugin = require('eslint-webpack-plugin');module.exports = {plugins: [new ESLintPlugin({extensions: ['js', 'jsx', 'ts', 'tsx'],fix: true,cache: true})]
};
自定義規則開發
創建簡單的自定義規則
// rules/no-console-log.js
module.exports = {meta: {type: 'suggestion',docs: {description: 'Disallow console.log statements',category: 'Best Practices',recommended: false},fixable: 'code',schema: []},create(context) {return {CallExpression(node) {if (node.callee.type === 'MemberExpression' &&node.callee.object.name === 'console' &&node.callee.property.name === 'log') {context.report({node,message: 'console.log is not allowed',fix(fixer) {return fixer.remove(node.parent);}});}}};}
};
使用自定義規則
// .eslintrc.js
module.exports = {rules: {'local/no-console-log': 'error'},plugins: ['local']
};// eslint-plugin-local/index.js
module.exports = {rules: {'no-console-log': require('./rules/no-console-log')}
};
性能優化
緩存配置
# 啟用緩存
npx eslint src/ --cache# 指定緩存文件位置
npx eslint src/ --cache --cache-location node_modules/.cache/eslint
并行處理
{"scripts": {"lint:parallel": "eslint src/ --cache --fix --max-warnings 0"}
}
忽略文件配置
# .eslintignore
node_modules/
dist/
build/
coverage/
*.min.js
*.bundle.js
public/
團隊協作最佳實踐
1. 統一配置管理
// eslint-config-company/index.js
module.exports = {extends: ['eslint:recommended','@typescript-eslint/recommended'],rules: {// 公司統一規則'indent': ['error', 2],'quotes': ['error', 'single'],'semi': ['error', 'always']}
};// 項目中使用
// .eslintrc.js
module.exports = {extends: ['@company/eslint-config']
};
2. 漸進式引入
// 第一階段:只啟用錯誤級別規則
module.exports = {extends: ['eslint:recommended'],rules: {// 只修復明顯錯誤'no-unused-vars': 'error','no-undef': 'error'}
};// 第二階段:添加警告級別規則
module.exports = {extends: ['eslint:recommended'],rules: {'no-unused-vars': 'error','no-undef': 'error','no-console': 'warn', // 新增警告'prefer-const': 'warn'}
};// 第三階段:提升為錯誤級別
module.exports = {extends: ['eslint:recommended'],rules: {'no-unused-vars': 'error','no-undef': 'error','no-console': 'error', // 提升為錯誤'prefer-const': 'error'}
};
3. CI/CD 集成
# .github/workflows/lint.yml
name: Lint
on: [push, pull_request]jobs:lint:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v2- uses: actions/setup-node@v2with:node-version: '16'- run: npm ci- run: npm run lint:check
常見問題與解決方案
1. 解析錯誤
問題:Parsing error: Unexpected token
解決:檢查解析器配置,確保支持使用的語法特性
module.exports = {parser: '@babel/eslint-parser',parserOptions: {ecmaVersion: 2021,sourceType: 'module',requireConfigFile: false}
};
2. 規則沖突
問題:ESLint 和 Prettier 規則沖突
解決:使用 eslint-config-prettier
module.exports = {extends: ['eslint:recommended','prettier' // 必須放在最后,覆蓋沖突規則]
};
3. 性能問題
問題:ESLint 運行很慢
解決:
- 啟用緩存:
--cache
- 使用 .eslintignore 忽略不必要的文件
- 考慮使用 eslint_d
# 安裝 eslint_d(ESLint 守護進程)
npm install -g eslint_d# 使用 eslint_d 替代 eslint
eslint_d src/
4. 內存溢出
問題:JavaScript heap out of memory
解決:增加 Node.js 內存限制
{"scripts": {"lint": "node --max-old-space-size=4096 node_modules/.bin/eslint src/"}
}