I'm using Prettier In my TypeScript project. I format all files on save in Visual Studio Code. I also configured a pre-commit git hook with Husky which checks the formatting of all files.
This is how my pre-commit
hook file looks like:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
cd ./MyApp/ClientApp
npx prettier --check .
Now comes the fun part. I work with files in MyApp/ClientApp
directory with VS Code, which does all the formatting on save. So far so good.
However, when I'm trying to make a commit, Prettier pre-commit hook gets executed and I get the following error:
git commit
Checking formatting...
[warn] src\dataTypes\numeratorObjectType.ts
[warn] src\viewModels\numeratorViewModel.ts
[warn] Code style issues found in the above file(s). Forgot to run Prettier?
husky - pre-commit hook exited with code 1 (error)
If I open these files in VS Code and save them, nothing happens as they have already been formatted.
So I execute Prettier manually by running the following command in MyApp/ClientApp
directory:
npx prettier --write .
This command outputs all the files, with the two problematic ones apparently reformatted:
I also see these files changed in git. However, git diff
shows nothing. When I execute git add .
, I'm getting the following warning:
The file will have its original line endings in your working directory. warning: LF will be replaced by CRLF
Which means these files only had issues with line endings. According to this thread, I set the following config parameters in my git repository:
git config core.autocrlf true
git config core.safecrlf false
It seems to make the warning with CRLF disappear when doing git add
, but it still doesn't solve the issue with Prettier. It still shows code style issues, even though there are no real differences/styling issues in the files.
I'm on Windows, as that might be important I guess.
Any idea what can be wrong here? Currently, checking Prettier formatting on pre-commit hook makes no sense.
After digging the issue more and thanks to comments from @eDonkey and @torek, I found a solution. I tested it for 2 days and it seems to work.
Please note, that this solution probably works for a project with Windows-only developers. If all of you are on Mac/Linux, you'd probably want to use LF instead of CRLF. If the team is mixed, I'm not sure there's a perfect solution here.
First, configure git
to not do CRLF -> LF conversion:
git config core.autocrlf false
Next, configure Prettier to use CRLF as the end of line character. You can do it by adding the following setting into Prettier's config file:
"endOfLine": "crlf"
If some of your files have already had the LF line endings, you might need to convert them to CRLF. It's enough to use npx prettier --write .
for that.
The only thing I noticed is that git
now adds ^M
character at the end of each line:
But it's not an issue for me.