Standardizing the code format before committing to GitHub
When working as a team, having a consistent coding structure and format is very important. Imagine a scenario where someone in the team installs a formatter while others don't. This results in commits that appear to have significant changes, but in reality, they only involve minor formatting differences, such as spaces and quote styles. Here comes the automation that I personally use for most of my projects and decided to write it down as a blog so that I could share it with future developers or even my future self.
Step 1: Install the dependencies
npm install -D husky lint-staged eslint prettier
Step 2: Create config for Prettier
{
"singleQuote": true,
"semi": true,
"printWidth": 100,
"trailingComma": "all",
"endOfLine": "auto"
}
Use the following to format the code:
npx prettier --write .
You may add the following to the scripts
section of package.json
so that you can run npm run format
to format manually all files while npm run lint-staged
to check prettier on the staged files which is what we want to do in the end of the tutorial.
"scripts": {
// Other default scripts
"format": "prettier --write .",
"lint-staged": "lint-staged"
},
"lint-staged": {
"*": "prettier --write"
},
At this step, you would see that you have almost all files with corrections. You may want to commit it and save it.
Step 3: Automate this process every time you have new code to commit
Pre-commit hooks allow us to run a set of commands before the commit is finalized. We will be setting up the pre-commit hook to run Prettier every time we are about to commit. We will be using Husky to achieve this.
Initialize Husky:
npx husky-init
You may delete the .husky/_
folder as it is not being used in this example. We are only using the pre-commit feature.
Update the file below:
npm run lint-staged
Now, whenever we run git commit
, all the defined scripts will run before the commit finalizes. You may now proceed to change the format by tweaking the .prettierrc.json
file.