How to Auto Format Code in Visual Studio Code
Keeping your code clean and consistently styled is essential for readability and collaboration. This article provides a quick, step-by-step guide on how to automatically format an entire document in Visual Studio Code (VS Code) using keyboard shortcuts, configuring the “Format on Save” feature, and setting up your default code formatter.
Method 1: Use the Keyboard Shortcut
The fastest way to format your active document is by using a built-in keyboard shortcut. Open the file you want to format and press:
- Windows:
Shift + Alt + F - macOS:
Shift + Option + F - Linux:
Ctrl + Shift + I
Alternatively, you can open the Command Palette by pressing
Ctrl + Shift + P (or Cmd + Shift + P on Mac),
typing “Format Document”, and pressing
Enter.
Method 2: Enable Format on Save
You can configure VS Code to automatically format your file every time you save your work.
- Open the Settings menu by pressing
Ctrl + ,(orCmd + ,on Mac). - In the search bar at the top of the Settings tab, type “Format on Save”.
- Locate the setting labeled Editor: Format On Save and check the box to enable it.
Once enabled, simply saving your file (Ctrl + S or
Cmd + S) will automatically format the entire document.
Method 3: Configure Your Default Formatter
If you have multiple formatting extensions installed (such as Prettier, Beautify, or language-specific linters), you need to set a default formatter to ensure consistent behavior.
- Right-click anywhere inside your document.
- Select Format Document With… from the context menu.
- Click on Configure Default Formatter… at the bottom of the dropdown list.
- Select your preferred formatter (e.g., Prettier - Code formatter) from the list.