Make Your Code Beautiful With Prettier

December 7, 2018
Read time 6 minutes

I have a newsletter! ✍

Subscribe so I can send you updates on new blog posts, videos, and anything else that I think you should know!

I'm a fan of cleanliness. I like a clean desk and a clean room. My desk at work is pretty sparse and minimal. I try and avoid clutter as it helps me find whatever it is I need at the moment I need it.

One of my most disliked tasks is having to clean up my apartment. Inevitably my apartment gets messy - that's just the unhappy side effect of living there and using it every day.

And as the clutter and disarray increases the need for me to take out the trash, and throw out the pile of mail grows as well.

I won't lie - every so often I get my apartment professionally cleaned. At a certain point I have to throw in the towel and just outsource that work to someone who does it better.

It's one of the best feelings in the world coming home to a freshly cleaned apartment. Aside from there being no mess, no dirt, no clutter - it was cleaned by someone else. That is what gives it that special touch of awesomeness that always keeps me coming back for more.


At this point you may be asking yourself what in Sam Hill does this have to do with Prettier? Notwithstanding this being a blog post about code, I haven't even talked about code yet!

You see, Prettier is a professional cleaner for your code. It reduces clutter, cleans up messes, and makes your editor feel like the coziest place on earth.

Prettier helps me keep my code as clean as I keep my apartment.

Video

Before I go on with all the remaining words of this post I want to let you know that this is also in video form.

So if you're the type of person who enjoys watching a human face teach you a new thing then enjoy the embedded video below.

If not then, keep on reading!

What is it?

Let's expand on what Prettier is a little bit more and leave that analogy alone for a little while. I love my analogies but sometimes I need to just write in plain english what the heck I'm talking about.

The most concise description of what Prettier is comes from its website:

An opinionated code formatter

Prettier will take your code - JavaScript, CSS, HTML, JSX (the list goes on) - and format it in a consistent and clean manner.

Take for example this unformatted code that is uh, perhaps a little hard to read:

function sayHello
(
    times
) 
{
    const handler
    = () => {console.log(
        'Hello'
    );
    
        const nextTimes = times - 1 
    
                if (nextTimes > 0) { sayHello(nextTimes); } }
    
    
    
                    setTimeout(   handler,   1000
                );
            
}

sayHello(       3)

This code works (try it), but reading it is pretty hard. At least for me it is. I mean, I tried to make it hard to read. I succeeded for myself at least.

Now here's that same code after Prettier has formatted it.

function sayHello(times) {
  const handler = () => {
    console.log('Hello');

    const nextTimes = times - 1;

    if (nextTimes > 0) {
      sayHello(nextTimes);
    }
  };

  setTimeout(handler, 1000);
}

sayHello(3);

Prettier, no?

Opinionated

Prettier is opinionated by default. The reasoning behind this is to reduce the arguments that engineers have around code-style and formatting. If there's anything that coders love to argue about it's the color of the bike shed and how many blank lines should be between two function calls.

The less options Prettier has the less there is to argue about.

Why there are any options at all is that there are a few points of contention that no amount of opinons will sway an engineer. For example tabs or spaces, or single vs double quotes. Rather than limit who would use Prettier, the door was opened a little wider to be more inclusive to the community at large.

Why should you use Prettier?

Prettier makes your code consistent and easy to read. This makes it so that you can open any file in your application and instantly know the style idioms such that you can spend more time reading the code and less time understanding the format.

Take for example a book. You read books right? A book typically has one font. Every page is the same font, letting you focus on the words and stories and less time on the design and style of the print.

Imagine that the first page of a book was written in Arial. The next page was written in Comic Sans. The next page in Helvetica. The next page in Papyrus.

That would make for an extremely painful experience. Every page becomes adversarial - getting in the way of the content and preventing people from understanding what they're reading.

That's why Prettier is important. It makes all your code the same 'font' such that another engineer can spend more time on what the code is doing, and not where it shows up on the screen.

Teaching Tool

If you're a new programmer I doubly recommend using Prettier.

Prettier's style conventions are defined by industry wide best practices and behaviors. Such that when you are learning how to code and you have Prettier installed, it's as if there's senior engineer over your shoulder constantly giving you tips and advice on how your code should look.

This frees you up to worry about what you want your code to do. Letting you focus on more important things - like learning the language - and not learning its customs and conventions. Two things that are extremely hard to pick up in a vacuum.

Other reasons

Some other reasons why you should use Prettier:

  • Never have another argument with a co-worker about why their style is wrong and yours is right. Outsource that argument to Prettier and get back to making your app!
  • Can clean up existing legacy codebases. This is an echo of the same reason of consistency. Legacy code is rarely touched and if it hasn't been touched in a while it may be tricky to read. Run Prettier over that code and now you're in business!
  • Prettier stays up to date with community conventions. As style conventions evolve so does Prettier. And when Prettier makes a tweak to its format applying that change is as simple as re-running Prettier over your code.

How do I use it?

Prettier operates as a CLI tool. You install it into your local application and then run its CLI tool to format your code with Prettier.

You can also install Prettier as an editor plugin, which is my recommended way of using Prettier. I'm going to point you to the official Prettier editors page to read more information about how to get that setup, but once it's installed it makes for the best experience.

You write some code, hit save, and Prettier makes your code...pretty. It's tremendous.

If you want to get Prettier running via CLI it takes two steps:

  1. Install it: npm install --save-dev prettier
  2. Run it: npx prettier [opts] [filenames]

If you want to customize Prettier then you have one more step:

  1. Make a .prettierrc file and set your options.

Conclusion

Prettier has made me a better programmer by allowing me to focus on more important things like what my code is doing, not how it looks.

I love that I can write sloppy code that may be somewhat illegible, and Prettier comes along and makes everything clean and tidy.

Sometimes I have a lot of fun writing intentionally gross looking code (like above) and watching Prettier swoop in and make it look so fresh and so clean, clean.