Skip to content

Code Formatting

The main reason you want to standardize and enforce code formatting is to have consistent, easy to read code. It will also avoid spending time discussing code styles and formatting preferences during pull requests code reviews.

Solution: Prettier

Prettier is an opininated code formatter that can fully automatically format your code to follow a consistent style and is super easy to adopt. It might not format your code 100% you would like it, but it is very well worth the trade-off.

It is easy to integrate in most editors and has a large ecosystem of plugins for interoperability with other tools and frameworks.

Use a configuration file to choose your preferred formatting settings.

Use a .prettierignore file to ignore specific folders and extensions.

Start with a script task in your package.json, for example to run on your source folder:

"quality:format": "prettier --check --ignore-unknown src"

Recipies

Run Prettier in your Continuous Integration (CI)

For code formatting to be enforced for all new code, you have to run Prettier in check mode as part of your CI pipeline.

Here is an example for Github Actions for Prettier check using pnpm:

name: Continuous Integration
on:
pull_request:
branches:
- main
jobs:
quality-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install pnpm
uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version: lts/*
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Run code quality format check
run: pnpm exec prettier --check --ignore-unknown src

We are using the --ignore-unknown flag to avoid warnings for files explicitly unknown to Prettier.

Setup Prettier check as pre-push hook with Lefthook

Start by installing Lefthook with your favorite package manager.

Then for the first time setup run:

Terminal window
pnpm exec lefthook install

It will create a file called lefthook.yml, which we can configure like this for Prettier:

pre-push:
parallel: true
commands:
format:
tags: code-quality
files: git diff-tree --no-commit-id --name-only -r HEAD..origin/main
run: pnpm exec prettier --check --ignore-unknown {files}

Each time we will push code, it will compare our diff tree with our main branch and for changed files, it will run Prettier checks ensuring your code is formatted before you can push.