乐闻世界logo
搜索文章和话题

What is Prettier and how does it work for code formatting?

2月21日 16:45

What is Prettier and How It Works

Prettier is a popular code formatter that works by parsing code to generate an Abstract Syntax Tree (AST), then rewriting the code back to files using its own set of style rules. The core philosophy of Prettier is to enforce a unified code style, eliminating code style debates in team collaboration.

How It Works

  1. Parsing Phase: Prettier first parses the source code to generate an Abstract Syntax Tree (AST)
  2. Formatting Phase: Converts the AST to formatted code based on configured formatting rules
  3. Output Phase: Writes the formatted code back to the file

Core Features

  • Zero Configuration: Works out of the box with sensible default configurations
  • Multi-language Support: Supports JavaScript, TypeScript, CSS, HTML, JSON, Markdown, and many other languages
  • Integratable: Can be integrated with editors, CI/CD, Git hooks, and other tools
  • Deterministic: Same input always produces the same output
  • Limited Configurability: Prettier intentionally limits configurable options to avoid style debates between teams

Differences from Other Tools

Prettier focuses on code formatting and does not perform code quality checks. This is different from tools like ESLint, which primarily handles code quality checks and identifies potential issues.

Use Cases

  • Unifying code style during team collaboration
  • Code format checking in CI/CD pipelines
  • Automatic formatting in editors
  • Code formatting before Git commits

Prettier enforces a unified code style, allowing developers to focus on code logic rather than formatting issues, thereby improving development efficiency.

标签:Prettier