It’s Time To Tidy Up Your Code: How To Use VS Code Autoformat

If you are like me and like to have consistency in formating your code, this is definitely a must to have configuration.

By default, you can use VS code formatters with the shortcut Alt+Shift+F but, you can also configure it to format every time you save your file, like this:

How to enable autoformat on Visual Studio Code

There are two options to enable autoformat by UI and editing settings.json file, let’s check both:

How to edit autoformat option on VS Code User Interface

Open the menu File->Preferences->Settings and under Text Editor look for Formating and enable the option Format On Save choosing which option is better on Format On Save Mode .

If you’re using version control, you can choose to format changes only, this is particularly useful if you’re working on legacy code and don’t want to change a large file at once. For this option choose modificationsIfAvailable .

How to edit autoformat option on VS Code settings.json

To find settings.json file, open your Visual Studio Code and press F1:

Now type settings.json , open the file and add the section:

{
    "editor.formatOnSave": true,
    "editor.formatOnSaveMode": "modifications"
}

For the configurationFormat On Save Mode you can pick of the options below:

  • file
  • modifications
  • modificationsIfAvailable

This is what your file should look like:

This configuration applies to most part of the supported languages, like PowerShell, JSON, C#, and others.

How to autoformat Terraform files on Visual Studio Code

Although the configuration above works for most languages if you are using terraform you need additional configurations. The plugin also doesn’t have a UI for it, so we need to add the configuration manually in the file settings.json.

To do it, open again the settings.json file and add the following sections:

{
    "[terraform]": {
        "editor.defaultFormatter": "hashicorp.terraform",
        "editor.formatOnSave": true,
        "editor.formatOnSaveMode": "file"
    },
    "[terraform-vars]": {
        "editor.defaultFormatter": "hashicorp.terraform",
        "editor.formatOnSave": true,
        "editor.formatOnSaveMode": "file"
    }
}

Pay attention that you must add one section for Terraform, and one more for terraform-vars.

This is the final file:

Conclusion

Autoformatting is an easy and helpful option that will for sure help your team to have consistency and keep your codebase tidy and clean.

See you in the next post!