Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you format code on save in VS Code

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.
like image 631
Tomas Nikodym Avatar asked Sep 14 '16 15:09

Tomas Nikodym


People also ask

How do I arrange my code in VS Code?

The code formatting is available in Visual Studio Code (VSCode) through the following shortcuts or key combinations: On Windows Shift + Alt + F. On macOS Shift + Option + F. On Linux Ctrl + Shift + I.

How do I save code without formatting in VS Code?

TIL how to save a file on VSCode without auto formatting being applied: CMD + K S . This can be useful in situations where one is working in a repository and is not interested in having a big file auto formatted, just for the sake of a trivial change.

How do I save to beautify?

You can also configure this to run automatically when saving a file. To do this, go to File->Preferences->Settings: Under Text Editor, select Format On Save. Now when saving a file, it will be beautified.


2 Answers

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

Add the following to your settings.json file:

"editor.formatOnSave": true
like image 100
Tomas Nikodym Avatar answered Oct 08 '22 23:10

Tomas Nikodym


No need to add commands anymore. For those who are new to Visual Studio Code and searching for an easy way to format code on saving, kindly follow the below steps.

  1. Open Settings by pressing [Cmd+,] in Mac (or [Ctrl+,] in Windows/Linux) or using the below screenshot.

VS Code - Open Settings Command Image

  1. Type 'format' in the search box and enable the option 'Format On Save'.

enter image description here

You are done. Thank you.

like image 145
Balasubramani M Avatar answered Oct 08 '22 22:10

Balasubramani M