Curious how Prettier formats code? Learn how code formatters work under the hood using parsers, ASTs, and code printers. Build your own mini code formatter step by step.
Have you ever wondered how tools like Prettier, Black, or gofmt automatically format messy code into something beautifully consistent?
The secret lies in something called an Abstract Syntax Tree (AST). In this blog post, we’ll dive deep into how code formatters work under the hood—and even show you how to build a basic one yourself.
Whether you're a curious developer or want to build your own formatter, this guide will give you everything you need to get started.
A code formatter is a tool that rewrites source code based on specific styling rules—like indentation, line breaks, spacing, and bracket placement—without changing the code’s logic or functionality.
Examples include:
They work in three core steps:
An Abstract Syntax Tree (AST) is a structured, tree-like representation of your code. It breaks the code into meaningful components like functions, variables, and expressions.
Let’s use a simple JavaScript code snippet:
Program
└─ VariableDeclaration
└─ VariableDeclarator
├─ Identifier (greet)
└─ ArrowFunctionExpression
├─ Identifier (name)
└─ BlockStatement
└─ ReturnStatement
└─ BinaryExpression ('Hello ' + name)
Once you have an AST, a formatter can traverse it and apply formatting rules like:
For example:
After applying all formatting rules, the formatter prints the final output as a code string.
This is not just JSON.stringify(AST)—you need a custom printer that understands how to convert syntax trees into styled text.
Prettier uses a system called doc printing, where it builds up virtual layout rules before converting them into a string.
If you just want to format your code instantly—without dealing with ASTs or building tools—use CodeFormatting.com.