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 src"

Recipies

Setup Prettier in your Continuous Integration (CI)

The workflow is as simple as running your previously defined script step after installing dependencies on your Continuous Integration (CI).

For example, with Github Actions, add the following step:

- name: Run code quality format check
run: pnpm run quality:format

Run Prettier only on changed files

On a very large codebase, validating all files for code formatting can take a bit of time so I would recommend to only do it for changed files.

In that case, you need to configure the changed files action to run prettier against changed files only, here is an exmaple configuration with 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: Get changed files in source folder
id: changed-files
uses: tj-actions/changed-files@v45
- name: Install dependencies
run: pnpm install
- name: Run code quality format check
env:
ALL_CHANGED_FILES: ${{ steps.changed-files.outputs.all_changed_files }}
run: pnpm exec prettier --check --ignore-unknown ${ALL_CHANGED_FILES}

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.