How to format code on save in VS Code

code formattingvisual-studio-codevscode-settings

I would like to automatically format TypeScript code using the build-in formatter when I save a file in Visual Studio Code.

I'm aware of the following options, but none of them is good enough:

  • Format manually Shift + Alt + F
  • Format on type "editor.formatOnType": true
    • It formats the line when you press enter. Unfortunatelly, it leaves it unformatted when you mouse-click another line or press up/down arrow.
  • Use existing extension
    • I tried this one, but it does not seem to work too well.
  • Use beautify "beautify.onSave": true
    • It does not work with TypeScript
  • Write custom extension
    • It's tricky if you want to handle autosaves and builds correctly.

Best Answer

As of September 2016 (VSCode 1.6), this is now officially supported.

Add the following to your settings.json file:

"editor.formatOnSave": true