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:
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:
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:
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:
It will create a file called lefthook.yml
, which we can configure like this for Prettier:
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.