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:
- Open VS Code.
- Go to the Extensions panel (
Ctrl + Shift + X
). - Search for Prettier - Code formatter.
- 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:
- Open Settings (
Ctrl + ,
). - Search for
editor.defaultFormatter
. - 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:
- Open Settings (
Ctrl + ,
). - Search for
editor.formatOnSave
. - 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.