Auto-formatting a code helps us to automatically make our code more readable and consistent. It allows us to tidy up our code every time we save the changes, saving time and enhancing your workflow. While auto-formatting is not an in-built feature of Visual Studio Code, you can install a free extension that allows you to do this. This article shows how to auto-format code in Visual Studio Code.
Enable “Format on Save”?
The “Format On Save” feature allows your code to automatically be formatted every time you save it – note that an extension will later be installed for it function. This feature is disabled in Visual Studio Code by default. Follow the steps to enable it:
- From the top-level File menu, select Preferences, and from the sub-menu, select Settings. Alternatively, you can press Ctrl + , to open Settings.
- Under the “Text Editor” section, select the Formatting menu option.
- Enable Format On Save option.
Install the “Prettier” extension
- From the sidebar, open the Extensions tab.
- Search for Prettier and install the extension.
- We have to configure the Prettier extension in Visual Studio Code. Go to Settings. Under the “Text Editor” section, choose the Font menu option. Then, select Edit in settings.json.
- Look for the following lines of code in the editor:
editor.defaultFormatter": "esbenp.prettier-vscode
If this code is missing, add it to the code editor and save it by pressing Ctrl + S.
Auto-format code
Now that we have the “Format On Save” feature enabled, and have installed the “Prettier” extension, we can easily auto-format the code of most languages:
- Open the file you want to format. I will be using a dummy JavaScript file named “index.js” for this tutorial. I have kept the file unformatted.
- Save your program by pressing Ctrl + S. Your code will automatically be formatted. Compare it with the unformatted code above, and you will see the difference.