Setting up a Husky format pre-commit hook for Prettier in Angular projects

61 Views Asked by At

I'm following this tutorial to attempt to set up a Husky pre-commit hook for Prettier in a new Angular project.

Also this is what I want to happen, so maybe there's something else I'm missing for this...I want the project files to actually be formatted if the are not, so that the formatting of the committed files match the formatting of the files committed.

It says to configure Husky like this:

  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.ts": [
      "prettier - write",
      "git add"
    ]
  },

After installing Husky and Prettier (npm i -D husky prettier) I tried this out by creating a src/app/test.ts file with the following content:

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

And that performed a git add . && git commit -m "Test".

After doing so nothing was triggered. I was expecting the test.ts file content to be formatted by prettier, prior to it being committed.

How do we trigger the pre-commit hook?

1

There are 1 best solutions below

1
Ole On

OK - Here's the recipe.

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

Now run ( Per the prettier site option 1 instructions ):

npx mrm@2 lint-staged

The pre-commit file should now look like this:

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

Also change the permissions of the pre-commit husky file.

chmod u+x .husky/pre-commit

And in package.json add formatting for typescript files:

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