ESLint + Prettier: The "Golden Headband" of Code Standards
ESLint and Prettier are indispensable tools in modern front-end engineering, acting like a "tight band" that enforces code style consistency and identifies potential issues. Their roles are clearly divided: ESLint focuses on code quality checks, while Prettier specializes in formatting uniformity. When used together, developers can concentrate more on logic rather than style debates.
Why Code Standardization Tools Are Needed
In team collaboration, differences in code styles can lead to additional communication overhead. For example:
- Some use single quotes, others use double quotes
- Choosing between 2-space or 4-space indentation
- Whether to enforce omitting trailing semicolons
- Whether object curly braces should wrap to new lines
These disagreements can pollute code review processes and even trigger unnecessary arguments. Enforcing standards through tools can completely eliminate such issues.
Core Capabilities of ESLint
ESLint implements code quality checks through its rule system. Its core functionalities include:
- Syntax Error Detection: Identifying typos or syntax issues before runtime
// Error example: undeclared variable
function demo() {
consle.log('error') // ESLint error: 'consle' is not defined
}
- Code Style Enforcement:
// .eslintrc.js
module.exports = {
rules: {
'quotes': ['error', 'single'], // Enforce single quotes
'semi': ['error', 'always'] // Require semicolons
}
}
- Best Practice Guidance:
// Warning against using == instead of ===
if (age == '18') { // ESLint warning: Expected '===' and instead saw '=='
// ...
}
Prettier's Formatting Philosophy
Prettier adopts an "opinionated" design philosophy, offering minimal configuration while ensuring output consistency:
// Input (poorly formatted)
const user={name:'John',age:30,skills:['js','css']};
// After Prettier formatting
const user = {
name: "John",
age: 30,
skills: ["js", "css"]
};
Key features:
- Automatic code restructuring
- Unified string quotes
- Standardized indentation and line width
- Intelligent handling of long expression line breaks
Collaborative Configuration Solution
When working together, rule conflicts must be resolved. Recommended approach:
- Install necessary dependencies:
npm install eslint prettier eslint-config-prettier eslint-plugin-prettier -D
- ESLint configuration (.eslintrc.js):
module.exports = {
extends: [
'eslint:recommended',
'plugin:prettier/recommended' // Must be placed last
],
rules: {
// Custom rules
}
}
- Prettier configuration (.prettierrc):
{
"printWidth": 80,
"tabWidth": 2,
"singleQuote": true
}
Practical Workflow Example
Integrate with Git Hooks for pre-commit automatic checks:
- Install husky and lint-staged:
npm install husky lint-staged -D
- package.json configuration:
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,jsx}": ["eslint --fix", "prettier --write"]
}
}
Handling TypeScript Projects
Additional configuration for TS projects:
// .eslintrc.js
module.exports = {
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
extends: [
'plugin:@typescript-eslint/recommended',
'prettier/@typescript-eslint'
]
}
Custom Rule Strategies
Adjust rule strictness based on project needs:
// Loose mode (suitable for early-stage projects)
rules: {
'no-console': 'warn' // Allow console but show warnings
}
// Strict mode (enterprise projects)
rules: {
'no-console': 'error',
'complexity': ['error', 5] // Cyclomatic complexity limit
}
Common Issue Solutions
Issue 1: ESLint and Prettier rule conflicts
- Solution: Ensure eslint-config-prettier disables all conflicting rules
Issue 2: VSCode doesn't auto-format on save
- Check settings:
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
Issue 3: Certain files need exemption
- Add .eslintignore:
*.config.js
dist/
Advanced Integration Techniques
Integration with CI/CD pipelines:
# GitHub Actions example
name: Lint
on: [push]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npm install
- run: npm run lint
Custom parsers for special syntax:
// Parsing Vue single-file components
module.exports = {
parser: 'vue-eslint-parser',
extends: ['plugin:vue/recommended']
}
Performance Optimization
Speed-up methods for large projects:
- Incremental checking:
eslint --cache
- Limit check scope:
eslint --ext .js,.ts src/
- Parallel execution:
npm install eslint-plugin-unicorn -D
# Configure rules
rules: {
'unicorn/no-for-loop': 'error' // Replace for-loops with array methods
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn