There May Not Be a Better Way to Effortlessly Improve Code Quality than Using Prettier Code Formatting
Tags: javascript, node, react, beginners
Published: 2020-06-05 13:02:36

---
title: There May Not Be a Better Way to Effortlessly Improve Code Quality than Using Prettier Code Formatting
published: true
description: We all want higher-quality code. With Prettier, you can achieve this with minimal effort. Let me show you how.
tags: javascript, node, react, beginner
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/mcx35j5r7t8dj8dm2r50.png
canonical_url: https://typeofnan.dev/increase-quality-with-prettier/
---

We all want higher-quality code. With Prettier, you can achieve this with minimal effort.

<hr />

## If you enjoy this tutorial, please give it a 💓, 🦄, or 🔖 and consider:

- signing up for [my free weekly dev newsletter](https://buttondown.email/devtuts)
- subscribing to [my free YouTube dev channel](https://www.youtube.com/c/devtutsco?sub_confirmation=1)

<hr />

# What is Prettier?

Prettier is an opinionated code formatter that supports various languages. When applied to a supported file type, Prettier will automatically format the code in that file.

# Supported Languages

Currently, Prettier supports a bunch of different languages/frameworks on its own and also has community plugins for other languages.

## Supported By Prettier

- JavaScript
- JSX
- Flow
- TypeScript
- JSON
- HTML
- Vue
- Angular
- CSS
- Less
- SCSS
- GraphQL
- Markdown/MDX

## Supported By Prettier Plugins

- Java
- PHP
- PostgreSQL
- Ruby
- Swift
- TOML
- XML

# The Power of Format on Save

There are a couple different ways you can use Prettier:

- Using the command line interface (CLI) to format individual or groups of files
- Setting up your code editor/IDE to format files automatically (e.g., when you save a file).

I prefer automatically formatting on save because it _immediately_ gives you feedback. One of the most important pieces of feedback it gives you is **it won't format if you have a syntax error!** This is actually incredibly powerful. When you're in the flow of programming, it's critical to have different types of immediate feedback to let you know when you've made a mistake so you can quickly correct course. Prettier offers one of the quickest feedback loops that exists.

# Installing Prettier

Okay, enough of me gushing about the greatness of Prettier, let's start using it in an example.

<hr />

## Quick Caveats About This Example

- You _can_ install Prettier globally, but it's advised to install it locally in your project as a development dependency. That way, all developers will have it at the same version.
- This example assumes your project dependencies are managed by `yarn` or `npm`.
- This example assumes you're using VS Code, which is how we'll configure our "Format on Save" functionality. Other development environments likely have similar functionality, you just might have to look it up!

<hr />

### Step 1: create a new project directory

Let's create a project directory for our new project. I'm running these commands in bash but you can create new files and folders using whatever method you're comfortable with.

```bash
mkdir prettier-example
```

### Step 2: initialize yarn (or npm)

Next, we initialize a new project. If using yarn, simply run the `yarn` command:

```bash
yarn
```

If using npm, run the following command to initialize with the default configuration:

```bash
npm init -y
```

### Step 3: Install Prettier

Now we install Prettier. **Make sure to pin Prettier to an exact patch version!** Prettier can update their formatting preferences between patch versions, so pinning to a specific patch version prevents formatting differences between different developers.

Also, make sure to install Prettier as a dev dependency since it's a dev tool rather than something used in production.

Using yarn:

```bash
yarn add -D prettier@2.0.5
```

Or npm:

```bash
npm install --save-dev prettier@2.0.5
```

Let's also create an empty prettier configuration file in our directory. Create `.prettierrc.json` and just put an empty object in there:

**.prettierrc.json**

```json
{}
```

#### Install the Prettier Plugin for VS Code

Make sure to install the Prettier plugin for VS Code. Instructions can be found [here](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode).

### Step 4: Create a poorly-formatted file

Let's create a poorly formatted file. Make `index.js` in your project directory and put the following code in it:

```javascript
function greet  (){  
const myVar= 'hello'
     console.log(myVar)}
```

This snippet has all sorts of weird spacing.

### Step 5: Set VS Code to format on save

Go to _Settings_ in VS Code. You can find this under File > Preferences > Settings or you can just use the ctrl+comma shortcut (cmd+comma on Mac). Find the _Editor: Format On Save_ option and make sure it's checked.

![format on save](https://dev-to-uploads.s3.amazonaws.com/i/fow0by23iuqo71a0wr1m.png)

**Note:** Other editors should be able to format on save as well, you will just have to find some editor-specific instructions if you're not using VS Code.

### Step 6: Save your index.js file

Save your `index.js` file. If all goes well, your file should format correctly!

```javascript
function greet() {
  const myVar = "hello";
  console.log(myVar);
}
```

Note that our spacing looks correct. Additionally, Prettier added trailing semi-colons and changed our single quotes to double quotes. A lot of this is [configurable](https://prettier.io/docs/en/configuration.html) in our `.prettierrc.json` file if you don't like some of the changes!

# A More Impressive Example

Let's change our `index.js` file to have some really gnarly code. Try changing it to this:

```javascript
const navBarProps = {name:["John Doe", null],
displayMode: ["dark", "light"],timezone: ["ET", "CT", "MT", "PT"],
};

function allCombinations(obj) {let combos=[{}];
for(const[key, values] of Object.entries(obj)) {combos = combos.flatMap((combo) =>
values.map((value) => ({ ...combo, [key]: value })));}return combos;}

console.log(allCombinations(navBarProps));
```

That's really quite ugly. Now save the document.

```javascript
const navBarProps = {
  name: ["John Doe", null],
  displayMode: ["dark", "light"],
  timezone: ["ET", "CT", "MT", "PT"],
};

function allCombinations(obj) {
  let combos = [{}];
  for (const [key, values] of Object.entries(obj)) {
    combos = combos.flatMap((combo) =>
      values.map((value) => ({ ...combo, [key]: value }))
    );
  }
  return combos;
}

console.log(allCombinations(navBarProps));
```

Beautiful!

# Why This is So Important

Prettier helps you write more consistent code. You see patterns better when your code is formatted correctly. When your code _doesn't_ format on save, you start immediately recognizing when your code has errors.

Please consider using Prettier, it'll make your dev process much more enjoyable!