TypeOfNaN

There May Not Be a Better Way to Effortlessly Improve Code Quality than Using Prettier Code Formatting

Nick Scialli June 06, 2020🚀🚀 7 minute read

If you're enjoying this blog, please consider one or both of the following:

prettier logo

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

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.


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!

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.

mkdir prettier-example

Step 2: initialize yarn (or npm)

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

yarn

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

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:

yarn add -D prettier@2.0.5

Or npm:

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

{}

Install the Prettier Plugin for VS Code

Make sure to install the Prettier plugin for VS Code. Instructions can be found here.

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:

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

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!

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 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:

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.

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!


Nick Scialli

Nick Scialli is a software engineer at the U.S. Digital Service.

Subscribe to the mailing list!

If you like what I post here, please sign up to get updates and code insights in your inbox. I won't spam you and you can unsubscribe any time!

Powered by Buttondown.