Why I Recommend Using Prettier on Front End Projects

I think using prettier on your front end projects is a great idea.

Prettier is code formatting tool. When you run it over a file, it reformats it according to some configurable rules. You can configure most editors to run it on save, or put it in a git pre-commit hook.

  1. Removes need for thinking about (and arguing passionately discussing) formatting rules. Never see another comment in your pull request about indentation or lines being too long

  2. Code faster without having to think about formatting. Prettier lets me get really sloppy while typing out my thoughts. I don’t have to think about where I should put a line break, or a semicolon, or really ever press enter. I just hit save and watch it magically fix itself. Awesome!

    Video of prettier code formatting in action

  3. Catches syntax errors. Since I’m expecting the file to magically reformat, if I ever don’t see that happen I realize I goofed up something. I jump over to the Output tab in VS code and look at the prettier error message, which tells me where I forgot to close a <div> or whatever. This is usually faster than waiting for an angular compile to unhelpfully tell me it couldn’t parse a template due to an error in line 1 column 2340.

  4. Codebases using a consistent formatting are easier to read. You get used to how to skim around and don’t have to expend as much mental energy tracking things. Im sure theres a study around this.

  5. Version control diffs are cleaner: never see some tabs vs spaces nonsense messing up your diff view on github

My Current .prettierrc file

  • singleQuote rewrites all string literals in js/ts to use a single quote instead of double
  • printWidth breaks lines longer than 120 characters into multiple lines in a sane fashion.
  • tabWidth tells prettier how many spaces to use for indendation
  • useTabs sets it up to indent with spaces
  • semi means to always put in semicolons in javascript even where the spec makes them optional
  • trailingComma inserts commas after the last element in arrays
  • bracketSpacing puts spacing around

Note: on one-off cases you can turn off prettier for sections of code, but I have only needed this like twice in my life

There are more options available, but these have served me well across a dozen projects.

Configurating Visual Studio Code

  1. Grab my file linked above and paste it into the root of your project as .prettierrc
  2. Install the prettier extension
  3. Configurate vscode to format on save with prettier: Open settings and search for formatting. Pick esbenp.prettier-vscode from the list of extensions and check Format on save

    VS Code formatting settings for prettier