Integrate Prettier into git commit workflow

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

mkdir prettierdemo
cd prettierdemo
yarn init

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

function prettify() {
    console.log('Hello world');
}

Install it.

yarn add prettier --dev

Run it from command line.

./node_modules/.bin/prettier --write index.js

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

./node_modules/.bin/prettier 
--single-quote
--tab-width 4
--write
index.js

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.

git init

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.

yarn add lint-staged husky --dev

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

Set the precommit npm command to call lint-staged.

"scripts" {
  "precommit": "lint-staged"
}

Configure lint-staged as follows.

"lint-staged": {
  "*.js": [
    "prettier --single-quote --tab-width 4 --write",
    "git add"
  ]
}

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.

Related Posts

Leave a Reply

Your email address will not be published.