If you’ve ever played with Go, you are aware of the existence of gofmt, which is a tool that automatically formats Go source code. Basically, you run a CLI command, give it an input which can be a string of code or a path to a file, and it outputs code that conforms to a consistent style.

So you are probably asking yourself, why use a tool that automatically formats code? Well, there are many benefits such as:

  • Consistent code style across a codebase
  • Saves you time and energy
  • Clean up existing codebase
  • Stop discussions around proper style
  • Reduce the amount of style issues in PRs that result in broken builds
  • … and so on

In this blog post, I will introduce you to a tool called Prettier, which does the same thing as gofmt, but with support for many languages and DSLs. So far it supports:

  • JavaScript (including ES2017)
  • JSX
  • Flow
  • Typescript
  • JSON
  • CSS, LESS and SCSS
  • GraphQL
  • Markdown

with work in progress for:

  • Python
  • PHP
  • Swift
  • Java
  • PostgreSQL

Usage

It’s easy to start using Prettier in your project. Suppose you are in a directory that consists of a JavaScript file index.js.

Note: Before running the following commands, make sure you have installed yarn on your machine.

 

First install Prettier:

yarn add prettier --dev --exact

Then run it against index.js:

yarn prettier --write index.js

 

And that’s it. Now, every time the command is ran, it will format the code. So, let’s say inside index.js there is:

function test   () {
    const foo = 10
        let bar = "hello"
}

After the command is ran, the contents of index.js will change to:

function test() {
  const foo = 10;
  let bar = "hello";
}

Things that changed are removed blank spaces after the function name, semicolons were added and the code was properly indented.

But, Prettier also can be configured on how the code should be formatted. You can find the different options here.

There is also a playground so that you can try it immediately.

 

Aside from running it from the command line, Prettier can be set as a pre-commit git hook, so that every time before new code is committed it will be automatically formatted. Information on how to set that up, can be found at https://prettier.io/docs/en/precommit.html.

There is also rich editor support.

Closing thoughts

I hope that what I showed you will convince you to use Prettier in your projects. I think that it’s a great tool that aids a lot to the development workflow. Personally I am excited about the plugins feature, that currently is in beta, which allows adding support for more languages.

Happy pretty printing!

About Aleksandar Jovanov

was part of Keitaro