Prettier with a sample .prettierrc and explanation of options

A cute and smart dog wearing glasses
A dog with glasses ready to do new tricks

I’ve worked on a team of one for a very long time. I appreciate the level of autonomy that I have, but I’ve noticed now more than ever that it can facilitate bad habits and laziness. Luckily, in the modern era of coding there are tools that can help encourage (or flat out enforce) good habits in code formatting and style. My latest attempt to start cleaning up some bad habits is to use Prettier (an opinionated code formatter) in all my projects rather than selectively.

Rather than me going deep into the how and the why for using Prettier I’d recommend reading this explanation.

If you use VSCode like I do then you first need to install the Prettier extension.  Once you have done that you can try out the sample .prettierrc file below by placing it in the root of your project(s).  The .prettierrc file is the configuration file that will allow you to set the Prettier options in a way that makes sense for your project. I’m trying to mostly use defaults (i.e. good habits), but there are a few options I prefer, or they are so engrained in legacy code that I maintain that changing them would be a Herculean effort.

Once the .prettierrc file is in place…

To format a document in VSCode:

  1. Use a Shortcut:
    • Windows/Linux: Press Shift + Alt + F
    • Mac: Press Shift + Option + F
  2. Use the Command Palette:
    • Open the Command Palette with Ctrl + Shift + P (Windows/Linux) or Cmd + Shift + P (Mac).
    • Type "Format Document" and press Enter.
  3. Auto-format on Save (optional):
    • Go to Settings (Ctrl + , or Cmd + ,), search for "format on save", and enable it by checking Editor: Format On Save.

Below is a gist containing two files. The first file is the sample .prettierrc.  The second file is a README which actually includes the contents of the .prettierrc file and explains the options.

The gist:

You don’t have to use a .prettierrc file. You can set up your options directly in the Prettier extension’s settings. However, I’m using the .prettierrc file so it is clear what options are being enforced on any given project.