Our code should be properly formatted as this makes code more readable. However, every developer has her style of writing code. Due to this reason, files in the project could have different formatting. It is advisable to keep the formatting of code in the files uniform.
Visual Studio Code is one of the most popular editor. In this article we’ll see how to format the file once we save the changes. So there is no need to manually format the code. We’ll use Prettier extension to format code in file once the file is saved.
Step 1: Install Prettier extension
- Go to Extensions menu. This is usually the last option by default in the menu. If it is not visible, you can show it by using View > Extensions.
- Search for Prettier and install extension.
Step 2: Enable format on save
- Navigate to Settings menu. Use the navigation File > Preferences > Settings.
- Search Editor.
- Look for setting Format on Save. Enable this setting by selecting the checkbox.
Step 3: Set Prettier as default formatter
Add the following property in settings.json.
"editor.defaultFormatter": "esbenp.prettier-vscode"
settings.json is found in the installation directory of Visual Studio code. In Windows, the default directory is C:\users{username}\AppData\Local\Programs\Microsoft VS Code. However, this may be different in your machine. If you are unable to find setting.json, you can look for Edit in settings.json link in Settings menu. You can click on Edit in settings.json to open the file.
Step 4: Test your changes
Open any code file. Do some changes and save the file. Verify that the code file is auto formatted on save.