How to Configure Prettier in VS Code to Format Code on Save

Introduction

Prettier is a popular code formatter that helps maintain a consistent style across your projects. If you're using Visual Studio Code (VS Code), configuring Prettier to format your code automatically when saving can improve your workflow and keep your codebase clean. In this post, we'll walk through the steps to set up Prettier in VS Code.

Step 1: Install Prettier Extension

The first step is to install the Prettier extension in VS Code:

  1. Open VS Code.
  2. Go to the Extensions panel (Ctrl + Shift + X).
  3. Search for Prettier - Code formatter.
  4. Click Install.

Step 2: Set Prettier as the Default Formatter

Once installed, you need to configure VS Code to use Prettier as the default formatter:

  1. Open Settings (Ctrl + ,).
  2. Search for editor.defaultFormatter.
  3. Select Prettier - Code formatter from the dropdown list.

Alternatively, you can add the following setting in your settings.json file:

{
  "editor.defaultFormatter": "esbenp.prettier-vscode"
}

Step 3: Enable Format on Save

To ensure that Prettier formats your code automatically when saving, enable the Format On Save option:

  1. Open Settings (Ctrl + ,).
  2. Search for editor.formatOnSave.
  3. Check the box to enable it.

Alternatively, you can add this to your settings.json file:

{
  "editor.formatOnSave": true
}

Step 4: Configure Prettier Rules (Optional)

If you want to customize Prettier's formatting rules, you can create a .prettierrc file in your project's root directory and define your preferred settings. Example:

{
  "singleQuote": true,
  "semi": false,
  "tabWidth": 2,
  "trailingComma": "es5"
}

Conclusion

By following these steps, you have successfully configured Prettier in VS Code to format your code automatically when saving. This setup helps maintain code consistency, improves readability, and saves time on manual formatting.