Auto-formatting your JavaScript Codebase with Prettier

ยท

2 min read

While creating new JavaScript projects, I've found that I need to add Prettier to each one of them. Prettier is an awesome opinionated code formatter, with good enough defaults that I almost never need to configure it. It just works, and it looks good ๐ŸŽจ

I'm documenting this so that I can have a single place to refer to the next time. I'm also doing it because I honestly need to get back to producing content and I might as well start with something I find useful.

Also it's 2018 and you want to spend your time actually writing code not thinking about whether to use double or single quotes every single time ๐Ÿ˜…

After initialising your project and ensuring you have a package.json file, run the following command to install prettier:

carbon

That's enough to use prettier. It comes with nice defaults that work pretty well for most cases. However, if you must make changes to the config, here's the different Prettier config options.

The next part is configuring Prettier to work with Visual Studio Code, my preferred editor.

In Visual Studio Code, go to the extensions pane and search for Prettier - Code formatterโ€‹ and install the first extension in the search results.

Now you can format the particular file by using the formatting key combination. Mine is control + option + b and this formats the file.

Prettier has support for lots of files, but I mostly use it for JavaScript, JSX, JSON, HTML and CSS as those are the ones I work with regularly.

And that ends today's post. Hope you get to try out Prettier too, trust me, it's awesome.