How to Format YAML codes in VSCode
Windows:
To ensure correct spacing in YAML while editing in VS Code, follow these tips:
1️⃣ Enable YAML Formatting in VS Code
- Install the YAML extension by Red Hat (
redhat.vscode-yaml
). - Go to Extensions (
Ctrl + Shift + X
), search YAML, and install.
2️⃣ Configure VS Code for YAML Formatting
- Open VS Code settings (
Ctrl + ,
). - Search for
"yaml.format.enable"
and enable it.
Alternatively, manually add this in settings.json
:
3️⃣ Format YAML Using Prettier
- Install Prettier extension.
- Set Prettier as default formatter:
Go tosettings.json
and add: - Use
Shift + Alt + F
to format YAML files automatically.
4️⃣ Convert Tabs to Spaces in YAML
- Open your YAML file.
- Press
Ctrl + Shift + P
→ Search"Convert Indentation to Spaces"
. - Ensure
"Tab Size: 2"
is set for correct YAML indentation.
5️⃣ Validate YAML to Avoid Errors
- Open VS Code terminal and run:
- Install
yamllint
using:
✅ Example of Properly Indented YAML
MAC:
Here’s how to fix YAML indentation issues and automatically format YAML files in VS Code on Mac:
1️⃣ Install YAML Extension in VS Code
- Open VS Code.
- Press
Cmd + Shift + X
to open the Extensions panel. - Search for "YAML" (by Red Hat) and click Install.
2️⃣ Configure VS Code for YAML Formatting
- Open Settings (
Cmd + ,
). - Search for
"yaml.format.enable"
and enable it.
Or manually add this to settings.json:
- Open Command Palette (
Cmd + Shift + P
). - Search "Preferences: Open Settings (JSON)" and click it.
- Add the following:
3️⃣ Install Prettier for YAML Formatting
- Open Extensions (
Cmd + Shift + X
). - Search "Prettier - Code formatter" and install it.
Set Prettier as the default formatter:
- Open Settings (JSON) (
Cmd + Shift + P
→ "Preferences: Open Settings (JSON)"). - Add:
- Now, press
Shift + Option + F
to format YAML files automatically.
4️⃣ Convert Tabs to Spaces
- Open your YAML file in VS Code.
- Press
Cmd + Shift + P
, search "Convert Indentation to Spaces", and select it. - Set
"Tab Size: 2"
for correct YAML indentation.
5️⃣ Validate YAML to Avoid Errors
Install YAML Linter (optional, but helpful):
- Open Terminal (
Cmd + Space
→ Search "Terminal"). - Run:
- Validate YAML files:
✅ Example of Properly Indented YAML
No comments