How to Install and Configure Prettier in VSCode for Seamless Code Formatting
Prettier is a popular opinionated code formatter that ensures a consistent code style across your project. Integrating it with VSCode helps streamline code formatting, saving time and improving readability. Here’s how to install and configure Prettier in VSCode step by step.
Step 1: Install VSCode
If you haven’t already installed Visual Studio Code (VSCode), download it from the official website:
Step 2: Open VSCode
Once VSCode is installed, launch it.
Step 3: Install Prettier Extension
- Click on the Extensions icon located on the sidebar of VSCode or use the shortcut
Ctrl+Shift+X
(Windows/Linux) orCmd+Shift+X
(Mac). - In the search bar, type Prettier — Code formatter.
- Select the Prettier extension from the search results by Esben Petersen.
- Click the Install button.
Step 4: Set Prettier as the Default Formatter
- Press
Ctrl+,
(Windows/Linux) orCmd+,
(Mac) to open Settings. - In the search bar, type default formatter.
- Under Editor: Default Formatter, select Prettier — Code formatter from the dropdown menu.
- Enable Editor: Format On Save by checking the box. This ensures that Prettier will format your code automatically when you save the file.
Step 5: Configure Prettier in Settings (Optional)
If you want to customize how Prettier formats your code, follow these steps:
- Open Settings (Ctrl+, or Cmd+,).
- Search for Prettier.
- Here, you can adjust settings like tab width, single/double quotes, semi-colons, and trailing commas based on your preferences.
- You can also directly edit the settings.json file to configure Prettier by clicking the link Edit in settings.json at the top right of the settings menu. Add custom configurations like this:
{
"editor.formatOnSave": true,
"prettier.singleQuote": true,
"prettier.trailingComma": "all",
"prettier.tabWidth": 4
}
Step 6: Create or Edit a .prettierrc
File (Optional)
For project-specific configurations, create a .prettierrc
file in the root of your project. This allows team members to share Prettier settings across the project.
- In the VSCode Explorer, right-click on your project folder and choose New File.
- Name the file
.prettierrc
. - Inside the file, add your Prettier configuration. For example:
{
"singleQuote": true,
"semi": false,
"tabWidth": 2,
"trailingComma": "es5"
}
Step 7: Use Prettier to Format Code
Now that Prettier is set up, you can format your code manually by:
- Right-clicking in your code editor and selecting Format Document.
- Using the shortcut
Shift+Alt+F
(Windows/Linux) orShift+Option+F
(Mac).
Prettier will also format your code automatically each time you save a file if you enabled the Format On Save option in Step 4.
Step 8: Verify Prettier Installation
To ensure Prettier is working, open any code file in your project and save it. If your code is automatically formatted based on the Prettier settings, it means the installation and configuration were successful.