JavaScript tooling: prettier

September 26, 2018

Prettier is an awesome code formatter.

I was first exposed to code formatters when I was learning Golang. I thought gofmt was one of the most interesting aspects of the language. Finally, we could all format our code the same way and skip the endless discussions about style and where things should go. Prettier aims to do the same for JavaScript, and a bunch of other languages.

Prettier allows you to type messy code, press a key, and probably get it in a better shape than you would have done yourself.

Using their own example (but slightly shortened), you can transform:

// from:

foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis());

// to:

foo(
  reallyLongArg(),
  omgSoManyParameters(),
  IShouldRefactorThis()
);

Except when it doesn’t…

Prettier doesn’t have too many options, and the idea of configuring Prettier seems to go against the philosophy of the tool itself.

The setting that has the most significant impact on the final result is printWidth. The documentation itself warns about setting the value too high:

Prettier, on the other hand, strives to fit the most code into every line. With the print width set to 120, prettier may produce overly compact, or otherwise undesirable code.

printWidth defaults to 80, which felt claustrophobic… but higher values, ironically, will transform:

// from:

foo(
  reallyLongArg(),
  omgSoManyParameters(),
  IShouldRefactorThis()
);

// back to:

foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis());

I found a workaround: if you add a single line comment, you force Prettier into a situation where it cannot inline your code without getting rid of the comment (which it won’t):

// locked by the comment:

foo(
  reallyLongArg(), // ⏎
  omgSoManyParameters(),
  IShouldRefactorThis()
);

I use a ⏎ (Unicode character: carriage return) as a convention in my own code, but what you put in the comment is up to you.

Prettier is not a linter

Prettier will fix the format of your code, but it doesn’t have opinions about the quality of your code.

For example, Prettier would not complain about:

(read more)

Yes, you will probably still need ESLint. You will need to find a config that’s compatible with Prettier’s rules. I use airbnb-base with some tweaks. You can also check Integrating with ESLint.

Getting Started

Check Editor Integration for details.

Most integrations have 2 modes:

Depending on the state of the codebase you’re in, I find manual mode makes more sense; I don’t always want to reformat every file I touch.

Discuss on Twitter