Prettier is a code formatter. It improves code consistency. Often, we have developers with their own styles of writing code. And it is quite difficult to tell them something as silly as formatting. But with this new utility, we don’t need to have ground rules on code formatting. It is taken care for us. The following screenshot shows how it works.

Prettier in action

By default, it indents the code by two spaces. And uses double quotes for strings. As you can see from the options, we can customize this behavior.

Let us try out the shiny new utility in a sample project.

Formatting using Prettier

Create a new project

Accept defaults. In the index file, type some code like below.

Install it.

Run it from command line.

The above command formats the file with default options. We can pass more options as follows.

All good, but how do we secure our code using a pre-commit hook.

Git pre-commit hook

Git has hooks. A pre-commit hook runs before we commit our code into git. We will show how we can commit better code into Git.

Set a new git repo.

Install lint-staged and husky packages. husky adds git hooks. In our case, the pre-commit hook. lint-staged helps us run commands at the time of commit.

Make sure you add a .gitignore file. And add node_modules to it.

Set the precommit npm command to call lint-staged.

Configure lint-staged as follows.

When we commit a JavaScript file, prettier formats the file. And the modified file is added to the staged files.

The entire package.json file is available in a gist.

Integrate Prettier into git commit workflow
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *