How it works

Prettier formats your code in three steps:

First it parses the code to its abstract syntax tree (AST), getting ride of (almost) all the original formatting. Then it transform the AST into another tree using some opinionated rules to group code fragments in a hierarchy that defines where new lines can be inserted if necessary. Finally, it prints the intermediate tree to a string, choosing the best places to add line-breaks based on the max line length (the default is 80).

Let’s see, for example, how var x = foooo + baaar gets formatted.

First the input string is parsed to AST. The AST looks something like this:

The AST include details about “var”, “x”, “+”, “foooo” and “baaar”, but nothing about spaces, line-breaks, semicolons or any other stylistic stuff that doesn’t matter at runtime. This AST is used as input for the next step that generates a document tree like this one:

Here you can see again “var”, “x”, “foooo”, mixed with some spaces, semicolons and a few Prettier commands. The structure of this tree depends on the stylistic opinions of Prettier.

In this case, three Prettier commands are being used. line indicates that a line-break can be inserted if its needed, if not, a space will be inserted. indent increases the level of indentation (only if the content is printed on a new line). group marks items which the printer should try to fit on one line, if it doesn’t fit it will break the outermost group and try again. There are more commands, for example hardline identifies a line that will always be included in the output.