Prettier 和 ESLint 是兩個互補的工具,它們共同確保代碼的風格一致性和質量。Prettier 負責格式化代碼,而 ESLint 則執行更復雜的靜態分析和規則檢查。
2500G計算機入門到高級架構師開發資料超級大禮包免費送!
Prettier
作用:
自動化代碼格式化,確保代碼的縮進、括號、引號、換行等樣式一致。
不需要配置太多的規則,因為Prettier有一套默認的代碼風格。
支持多種編程語言,包括JavaScript、TypeScript、CSS、HTML等。
可以與ESLint集成,避免兩者規則沖突。
使用示例: 在項目根目錄下創建 .prettierrc
或 .prettierrc.json
文件來配置Prettier,例如:
{"printWidth": 80, // 行寬"tabWidth": 2, // Tab寬度"useTabs": false, // 是否使用制表符"semi": true, // 是否使用分號"singleQuote": true, // 使用單引號"trailingComma": "all", // 尾隨逗號"bracketSpacing": true, // 對象花括號之間是否有空格"jsxBracketSameLine": false // JSX標簽閉合花括號是否在同一行
}
然后在項目中安裝Prettier:
npm install --save-dev prettier
并在.gitignore文件中排除Prettier生成的臨時文件。
ESLint
#### 作用:
- 靜態代碼分析,檢測潛在的錯誤、代碼異味和不推薦的編程習慣。
- 提供豐富的自定義規則,可以檢查代碼風格、變量使用、代碼復雜度等。
- 可以與Prettier集成,先格式化再檢查,避免格式問題干擾實際的錯誤檢測。
使用示例: 創建 .eslintrc.js
或 .eslintrc.yaml
配置文件:
module.exports = {env: {browser: true,es2021: true,},extends: ['plugin:react/recommended','airbnb-base',],parser: '@typescript-eslint/parser',parserOptions: {ecmaVersion: 12,sourceType: 'module',ecmaFeatures: {jsx: true,},},plugins: ['@typescript-eslint','react',],rules: {'no-console': 'off', // 關閉禁止console.log的規則'import/no-unresolved': 'error', // 報告未解析的導入},
};
安裝ESLint及其相關的插件:
npm install --save-dev eslint eslint-plugin-react @typescript-eslint/parser @typescript-eslint/eslint-plugin
在項目中使用npx eslint
或配置IDE(如VSCode)的ESLint插件來進行實時檢查。
集成與自動化
通過eslint-plugin-prettier和eslint-config-prettier,可以在ESLint中集成Prettier:
npm install --save-dev eslint-plugin-prettier eslint-config-prettier
然后在.eslintrc.js
中添加以下內容:
module.exports = {// ...plugins: ['prettier'],extends: ['plugin:prettier/recommended'], // 使用Prettier的ESLint規則rules: {'prettier/prettier': 'error', // 把Prettier的規則設為錯誤級別// ...其他規則},
};
現在,當運行eslint --fix
時,ESLint會先應用Prettier的格式化,然后再執行自己的檢查。
樣例配置文件
.prettierrc (Prettier配置)
{"semi": true,"trailingComma": "none","tabWidth": 2,"singleQuote": true,"printWidth": 120,"jsxSingleQuote": true,"arrowParens": "avoid","htmlWhitespaceSensitivity": "css","endOfLine": "lf"
}
1.2 .eslintrc.js (ESLint配置)
javascript
module.exports = {env: {browser: true,es6: true,},extends: ['airbnb-base','plugin:@typescript-eslint/recommended','plugin:prettier/recommended',],parser: '@typescript-eslint/parser',parserOptions: {ecmaVersion: 2020,sourceType: 'module',},plugins: ['@typescript-eslint', 'prettier'],rules: {'prettier/prettier': 'error','no-unused-vars': 'warn','no-console': 'warn',},
};
集成到構建流程
使用husky和lint-staged進行提交前的檢查
安裝依賴:
npm install --save-dev husky lint-staged
在package.json
中添加如下配置:
"husky": {"hooks": {"pre-commit": "lint-staged"}
},
"lint-staged": {"*.ts?(x)": ["prettier --write", "eslint --fix"],"*.js?(x)": ["prettier --write", "eslint --fix"],"*.html": ["prettier --write"],"*.css": ["prettier --write"]
}
這樣,在每次提交前,lint-staged會自動運行Prettier和ESLint,格式化和修復代碼。
配置IDE
在Visual Studio Code、WebStorm或其他支持ESLint和Prettier的IDE中,安裝對應的插件并配置自動格式化和檢查。
自定義規則
ESLint的靈活性允許你創建自定義規則以滿足特定項目需求。在.eslintrc.js中添加自定義規則:
rules: {'your-custom-rule': 'error',// ...
}
創建一個lib或rules目錄,然后在其中定義你的自定義規則模塊。
常見問題與解決方案
沖突處理
有時,Prettier和ESLint的規則可能會沖突。在這種情況下,通常優先遵循Prettier的規則,因為它專注于代碼格式。如果你需要特定的ESLint規則,可以在.eslintrc.js中禁用Prettier的對應規則:
rules: {'prettier/prettier': ['error', { singleQuote: false }] // 禁用Prettier的單引號規則
}
性能優化
如果ESLint運行緩慢,可以考慮以下優化:
僅在必要時運行:例如,只在修改了相關文件后運行。
使用–cache選項:ESLint將緩存已檢查的文件,以加快后續運行速度。
使用.eslintignore文件:排除不需要檢查的文件和目錄。
使用ESLint的插件和共享配置
插件
@typescript-eslint
:為TypeScript提供額外的規則和錯誤修復。
eslint-plugin-import
:檢查導入順序和導出規范。
eslint-plugin-react
:針對React組件的特定規則。
eslint-plugin-react-hooks
:檢查React Hooks的使用。
eslint-plugin-prettier:使ESLint與Prettier協同工作,防止沖突。
安裝這些插件:
npm install --save-dev eslint-plugin-import eslint-plugin-react eslint-plugin-react-hooks @typescript-eslint/eslint-plugin
共享配置
eslint-config-airbnb
:Airbnb的編碼風格指南。eslint-config-prettier
:禁用與Prettier沖突的ESLint規則。
在.eslintrc.js
中使用共享配置:
module.exports = {extends: ['airbnb','airbnb-typescript','plugin:@typescript-eslint/recommended','plugin:import/recommended','plugin:react/recommended','plugin:react-hooks/recommended','plugin:prettier/recommended',],// ...
};
定制共享配置
根據項目需求,可以自定義共享配置,例如:
module.exports = {extends: ['airbnb','airbnb-typescript','plugin:@typescript-eslint/recommended','plugin:import/recommended','plugin:react/recommended','plugin:react-hooks/recommended','plugin:prettier/recommended',],rules: {'import/prefer-default-export': 'off', // 關閉非默認導出的警告'@typescript-eslint/explicit-module-boundary-types': 'off', // 關閉類型聲明的警告// 添加或修改其他規則},
};
高級用法
配置環境
在.eslintrc.js
中設置環境變量,以便啟用特定環境下的規則:
env: {browser: true,es6: true,node: true,jest: true,
}
使用ESLint的overrides字段
overrides允許你為特定類型的文件或目錄指定不同的規則。例如,為.test.js文件添加獨立的規則:
module.exports = {overrides: [{files: ['**/*.test.js'],rules: {'no-unused-expressions': 'off', // 在測試文件中關閉表達式不使用警告},},],// ...
};
部署到持續集成(CI)
將ESLint和Prettier集成到持續集成流程中,確保所有提交的代碼都符合標準。例如,在GitHub Actions中配置:
name: Lint and Formaton:push:branches:- mainpull_request:jobs:lint:runs-on: ubuntu-lateststeps:- name: Checkout codeuses: actions/checkout@v2- name: Setup Node.jsuses: actions/setup-node@v2with:node-version: '14.x'- name: Install dependenciesrun: npm ci- name: Lint and formatrun: npm run lint
2500G計算機入門到高級架構師開發資料超級大禮包免費送!