How to Automatically Format Your Code with Prettier in Visual Studio Code

May 14, 2024Share
blog picture -How to Automatically Format Your Code with Prettier in Visual Studio Code

For developers, maintaining consistent code formatting isn't just about aesthetics; it's essential for readability and team collaboration. That's where Prettier comes into play—an "opinionated" code formatter that enforces a consistent style by reformatting your code according to defined rules. This blog will guide you through setting up Prettier in Visual Studio Code (VS Code) to automatically format your code upon saving.

Step 1: Install Prettier

To begin, you'll need to install Prettier in VS Code. This can easily be done via the VS Code Marketplace. Search for "Prettier - Code formatter" in the marketplace or directly follow this link and click 'Install'.

blog picture -prettier vscode marketplace

Step 2: Enable Format on Save

By default, Prettier does not automatically format your code on save. To enable this feature:

Open the command palette in VS Code with Ctrl+Shift+P (or Cmd+Shift+P on Mac).

Type "Open User Settings" and select it.

In the search bar at the top of the Settings tab, type "Format On Save".

Check the box for Editor: Format On Save to enable automatic formatting.

blog picture -prettier format on save

Now, whenever you save a file, Prettier will format your code according to the predefined rules.

Step 3: Avoid Formatting on Save for Shared Code

If you're working with code that others might not want automatically reformatted, you can save without formatting. To do this:

Open the command palette again with Ctrl+Shift+P (or Cmd+Shift+P on Mac).

Type "Save without Formatting" and select it.

This prevents your edits from being marked as changes due to formatting differences in version control systems like Git.

Tags: Professional, Tips