How to Auto Format Code in Visual Studio Code

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:

  1. From the top-level File menu, select Preferences, and from the sub-menu, select Settings. Alternatively, you can press Ctrl + , to open Settings.

    Settings
    Go to File<Preferences
  2. Under the “Text Editor” section, select the Formatting menu option.

    Settings Window
    From Text Editor section, choose Formatting option.
  3. Enable Format On Save option.

    Format On Save
    Check Format On Save option.

Install the “Prettier” extension

  1. From the sidebar, open the Extensions tab.

    Extensions Tab
    Select the Extensions button from the sidebar on Visual Studio Code’s left side.
  2. Search for Prettier and install the extension.

    Prettier
    Look for Prettier in the marketplace and then install it.
  3. 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.

    Settings JSON
    Go to Settings>Text Editor>Font menu. Then, under the Font Weight option, click on Edit in settings.json.
  4. 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.

    Configure Prettier
    Look for the configuration code in the settings.json file.

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:

  1. 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.

    Dummy File
    Open the file or code you want to format.
  2. 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.

    Auto Format
    Save your file or code to auto-format it.

Was this article helpful?

Leave a Comment