Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prettier extension not formatting code on file save

I have installed prettier extension for VS Code, set it as default formatter, also set format on save to true in VS Code's settings file, and files are set to be saved automatically after some time delay.

"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"files.autoSave": "afterDelay"

But prettier is not formatting my code when file is saved automatically after 2 seconds delay. Code is only formatted if i:

  • manually format the code using option + Shift + F keyboard shortcut.
  • press command + S

Here's my .prettierrc file

{
    "trailingComma": "es5",
    "tabWidth": 4,
    "semi": true,
    "singleQuote": true
}

How can i make prettier format my code automatically on file save?

like image 797
Yousaf Avatar asked May 20 '20 21:05

Yousaf


People also ask

Why is VS Code not formatting on save?

Usage. To automatically format the file on save, In Visual Studio Code, press Control + Shift + P or Command + Shift + P (Mac) to open the command palette and type setting and then select Preferences: Open User Settings option. Search for format on save setting and check the checkbox.

How do I enable Prettier in VS Code on save?

Open the VS Code Settings menu by tapping “Command + ,(comma)” if you use a Mac. Click on “Control + ,(comma)”, if you are a Windows user. Go to the search bar and input “Editor: Format on Save.” Ensure it has a checkmark.


1 Answers

After some searching, i found out that the following setting

"editor.formatOnSave": true

only works if:

  • Code formatter is available.
  • The files are NOT set to be saved after a delay.
  • And the editor must not be shutting down.

I had set the prettier as the default formatter using the following setting:

"editor.defaultFormatter": "esbenp.prettier-vscode"

But I had set files to be saved automatically after a delay as specified in the following setting:

"files.autoSave": "afterDelay"

This setting was the cause of the problem in my case.

"files.autoSave" setting can have one of the following values:

  • "off": A dirty editor is never automatically saved.
  • "afterDelay": A dirty editor is automatically saved after the configured files.autoSaveDelay.
  • "onFocusChange": A dirty editor is automatically saved when the editor loses focus.
  • "onWindowChange": A dirty editor is automatically saved when the window loses focus.

Setting "files.autoSave" to any possible value other than "afterDelay" will fix the issue. I solved this issue by setting "files.autoSave" to "onFocusChange".

like image 170
Yousaf Avatar answered Sep 20 '22 20:09

Yousaf