| name | code-style |
| description | 代码风格检查与自动格式化。Use when (1) 配置 linter/formatter, (2) 修复代码风格问题, (3) 设置 pre-commit hooks, (4) 统一团队代码风格 |
Code Style & Formatting
Objectives
- Configure and run code formatters (Prettier, Black, Ruff)
- Set up linters (ESLint, Ruff, mypy)
- Fix style violations automatically
- Establish pre-commit hooks for consistency
Python Style
Tools
- Ruff: Fast linter + formatter (replaces Black, isort, flake8)
- mypy: Static type checker
- pyproject.toml: Configuration file
Configuration
[tool.ruff]
line-length = 100
target-version = "py310"
[tool.ruff.lint]
select = [
"E",
"W",
"F",
"I",
"N",
"UP",
]
ignore = ["E501"]
[tool.mypy]
python_version = "3.10"
strict = true
warn_return_any = true
warn_unused_configs = true
Commands
ruff format .
ruff check --fix .
mypy src/
ruff format . && ruff check --fix . && mypy src/
TypeScript/JavaScript Style
Tools
- Prettier: Code formatter
- ESLint: Linter
- TypeScript: Type checker
Configuration
export default [
{
files: ["**/*.{ts,tsx}"],
rules: {
"no-console": "warn",
"no-unused-vars": "error",
"@typescript-eslint/no-explicit-any": "error",
"react-hooks/rules-of-hooks": "error",
},
},
];
{
"semi": true,
"singleQuote": false,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100
}
Commands
npm run format
npx prettier --write "src/**/*.{ts,tsx}"
npm run lint
npx eslint --fix "src/**/*.{ts,tsx}"
npx tsc --noEmit
Style Rules
Formatting
- Line length: 100 characters (Python and TypeScript)
- Indentation: 4 spaces (Python), 2 spaces (TypeScript)
- Quotes: Double quotes (TypeScript), either (Python, but consistent)
- Trailing commas: Yes (for multi-line)
- Semicolons: Yes (TypeScript)
Naming (enforced by linters)
class UserService:
MAX_RETRIES = 3
def get_user(self):
user_id = 123
return user_id
class UserService {
private readonly maxRetries = 3;
getUser(): User {
const userId = 123;
return user;
}
}
Imports
import os
import sys
from pathlib import Path
import requests
from fastapi import FastAPI
from src.core.models import User
from src.services.auth import AuthService
import { useState, useEffect } from "react";
import type { User } from "@/types";
import { Button } from "@/components/ui/button";
import { authService } from "@/services/auth";
Type Annotations
Python
def get_user(user_id: int) -> User | None:
"""Get user by ID."""
return db.query(User).get(user_id)
def process_items(items: list[str]) -> dict[str, int]:
return {item: len(item) for item in items}
TypeScript
function getUser(userId: number): User | null {
return db.users.find(userId);
}
const users = await fetchUsers();
Documentation
Python Docstrings
def calculate_score(
user_id: int,
weights: dict[str, float],
normalize: bool = True
) -> float:
"""Calculate weighted score for user.
Args:
user_id: User identifier
weights: Feature weights mapping
normalize: Whether to normalize to [0, 1]
Returns:
Calculated score
Raises:
ValueError: If user not found
"""
pass
TypeScript JSDoc
function calculateScore(
userId: number,
weights: Record<string, number>,
normalize = true,
): number {
}
Pre-commit Hooks
Python (using pre-commit)
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.9
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.8.0
hooks:
- id: mypy
additional_dependencies: [types-requests]
Install: pre-commit install
TypeScript (using husky + lint-staged)
{
"lint-staged": {
"*.{ts,tsx}": ["eslint --fix", "prettier --write"]
}
}
Install: npx husky install && npx husky add .husky/pre-commit "npx lint-staged"
Auto-fix Workflow
When style issues are found:
-
Run formatter first (fixes most issues)
ruff format .
prettier --write .
-
Run linter with auto-fix
ruff check --fix .
eslint --fix .
-
Check remaining issues
ruff check .
eslint .
-
Type check
mypy src/
tsc --noEmit
Common Issues
Python
- Import order: Let Ruff handle it automatically
- Line too long: Use formatter, or add
# noqa: E501 if necessary
- Type errors: Add type annotations or use
# type: ignore[error-code]
TypeScript
- Any types: Replace with proper types or use
unknown
- Unused vars: Remove or prefix with
_ if intentionally unused
- Missing return types: Add explicit return type annotations
IDE Integration
VS Code
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
Validation Checklist
Before committing:
Project-Specific Rules
Check for project overrides in:
pyproject.toml (Python)
eslint.config.js (TypeScript)
.prettierrc (TypeScript)
.vscode/settings.json (IDE settings)
Load these files first to understand project conventions.