Skip to content

Code Quality Tools: ESLint & Prettier

Qianhe Chen edited this page Nov 9, 2024 · 1 revision

Code Quality Tools: ESLint & Prettier

Overview

We use ESLint and Prettier to maintain code quality and consistency. ESLint helps catch bugs and enforce coding standards, while Prettier ensures consistent code formatting.

Core Differences

Feature ESLint Prettier
Purpose Code quality rules & error detection Code formatting
Fixes Logic, syntax, and style issues Formatting only
Configurability Highly configurable rules Limited formatting options
Focus Find problematic patterns Make code pretty

ESLint

What it Does

  • Finds and fixes problems in your JavaScript/TypeScript code
  • Enforces coding style
  • Catches bugs before they run
  • Ensures code quality

Basic Configuration

// .eslintrc.js
module.exports = {
  root: true,
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier' // Must be last
  ],
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  rules: {
    'no-console': 'warn',
    'no-unused-vars': 'error',
    '@typescript-eslint/explicit-function-return-type': 'error'
  }
}

Common Rules

// Bad code ESLint will catch
const unused = "I'm never used";        // no-unused-vars
console.log("debugging leftover");      // no-console
if (someVar == null) { }               // eqeqeq

// Good code
const used = "I'm used";
logger.info("proper logging");
if (someVar === null) { }

Prettier

What it Does

  • Formats code automatically
  • Ensures consistent style
  • Ends style debates
  • Works with many file types

Basic Configuration

// .prettierrc
{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2
}

Formatting Examples

// Before Prettier
const messy_code    = "very messy"  ;
function longFunction(a,    b,c){
    return a+b+c}

// After Prettier
const messy_code = 'very messy';
function longFunction(a, b, c) {
  return a + b + c;
}

Integration

Working Together

// .eslintrc.js
module.exports = {
  extends: [
    'eslint:recommended',
    'prettier' // Prettier must be last
  ],
  plugins: ['prettier'],
  rules: {
    'prettier/prettier': 'error'
  }
}

VS Code Setup

// settings.json
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  }
}

Git Hooks (optional)

// package.json
{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,ts,tsx}": [
      "eslint --fix",
      "prettier --write"
    ]
  }
}

Common Commands

# Install
pnpm add -D eslint prettier @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-config-prettier

# Check issues
pnpm eslint .
pnpm prettier --check .

# Fix issues
pnpm eslint --fix .
pnpm prettier --write .

🔍 Further Reading

For detailed configuration options and rules: