ข้ามไปยังเนื้อหา

Linting & Formatting — ruff และ black

ในโลก TypeScript คุณต้องเซ็ต tool สองตัว คือ eslint คุมกฎด้าน code quality และ prettier คุม style ทั้งคู่มี config คนละไฟล์ คำสั่ง CLI คนละชุด และบางทีก็ตีกันเองด้วย

นักพัฒนา Python แต่ก่อนก็ใช้วิธีแยกเหมือนกัน: flake8 (lint) + black (format) แต่ ruff — เปิดตัวในปี 2022 และเขียนด้วย Rust — ตอนนี้แทนที่ทั้งคู่ หนึ่ง tool หนึ่ง section config ใน pyproject.toml และรันใน milliseconds บน codebase ทั้งหมด

รันในเทอร์มินัลของคุณ — ไม่ต้องใช้ Playground สำหรับคำสั่ง CLI

Terminal window
# ติดตั้ง (เพิ่มใน dev dependencies ของ project)
pip install ruff
# หรือด้วย uv:
uv add --dev ruff
# Lint ทั้ง project
ruff check .
# แก้ไข lint violations ที่แก้ได้อัตโนมัติ
ruff check --fix .
# Format ทั้ง project (แทนที่ black)
ruff format .
# ตรวจสอบ formatting โดยไม่เขียนไฟล์ (โหมด CI)
ruff format --check .
TypeScript
// .eslintrc.js (or eslint.config.js)
module.exports = {
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
rules: {
'no-unused-vars': 'error',
'@typescript-eslint/no-explicit-any': 'warn',
},
};
// .prettierrc
{
"singleQuote": true,
"semi": false,
"printWidth": 88
}
Python
# pyproject.toml — ไฟล์เดียวสำหรับทุกอย่าง
[tool.ruff]
line-length = 88
indent-width = 4
[tool.ruff.lint]
# E/W = pycodestyle F = pyflakes I = isort UP = pyupgrade
select = ["E", "F", "I", "UP"]
ignore = ["E501"] # line-too-long (จัดการโดย formatter)
[tool.ruff.format]
quote-style = "double" # ตรงกับค่าเริ่มต้นของ black

ก่อนจะมี ruff format ตัว black คือมาตรฐาน de-facto และยังเจอได้ทั่วไปในโปรเจกต์ Python ที่มีอยู่เดิม จุดขายคือ opinionated โดยตั้งใจ ปรับแต่งได้แทบไม่มีอะไรเลย เหมือน prettier ที่ล็อก --no-semi ไว้ตายตัว ถ้ารับช่วงโปรเจกต์ที่ใช้ black อยู่แล้วก็ใช้ต่อไป อย่าเอาสองตัวมาผสมกัน

Terminal window
pip install black
# Format ไฟล์เดียว
black src/main.py
# Format ทั้ง project
black .
# โหมด check-only สำหรับ CI
black --check .
TypeScript
# Node / TypeScript workflow
npx eslint src/ --fix
npx prettier src/ --write
# หรือด้วย script รวมใน package.json:
# "lint:fix": "eslint src/ --fix && prettier src/ --write"
Python
# Python workflow — ruff ทำทั้งสองอย่าง
ruff check --fix .
ruff format .
# หรือในครั้งเดียว (check แล้ว format):
ruff check --fix . && ruff format .
# Makefile target (pattern ที่พบบ่อย):
# lint:
# ruff check --fix . && ruff format .

Playground note: ruff และ black ทำงานกับไฟล์และต้องการ terminal environment รันคำสั่งข้างต้นในไดเรกทอรี project ของคุณ

tool ตัวใดแทนที่ทั้ง flake8 (lint) และ black (format) ใน Python project สมัยใหม่?
คำสั่งใด format ทั้ง Python project ด้วย ruff โดยไม่แก้ไขไฟล์ (โหมด CI)?
ruff อ่าน configuration จากไฟล์ใด?