Format Angular Project Git Staged Files with Prettier on Commit

Ole Ersoy
2 min readMar 18, 2024

--

Image by Anja from Pixabay

Scenario

We want to make sure that all our Angular files are formatted with prettier before they are committed.

Approach

We will use Husky for this.

Create a new Angular project, install Husky and Prettier, and initialize Husky.

ng new ngtestprettierhook --style=scss
cd ngtestprettierhook
npm i -D prettier husky
npx husky init

Also since this is Angular we want to run our tests in the .husky/pre-commit file. Change it to look like this:

ng test --watch=false --browsers=ChromeHeadless

Then install and initalize lint-staged as described in the Prettier documentation.

npx mrm@2 lint-staged

The .husky/pre-commit file should now look like this.

ng test --watch=false --browsers=ChromeHeadless
npx lint-staged

We also need to give the pre-commit file executable permission.

chmod u+x .husky/pre-commit

Configure lint-staged to add include for Typescript in package.json .

"lint-staged": {
"*.{js,ts,css,md}": "prettier --write"
}

Now create a src/app/test.ts file with this content.

export class Test { nf:string = "not formatted"     }

And run git add . && git commit -m "Test" .

The test.ts file is formatted as expected.

--

--