Search code examples
visual-studio-codeformattingprettier

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?


Solution

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