Tutorial

How To Format Code with Prettier in Visual Studio Code

Updated on March 29, 2024
English
How To Format Code with Prettier in Visual Studio Code

Introduction

Formatting code consistently is a challenge, but modern developer tools make it possible to maintain consistency across your team’s codebase automatically.

In this article, you’ll set up Prettier to automatically format your code in Visual Studio Code, also known as VS Code.

For demonstration purposes, here’s the sample code you will be formatting:

const name = "James";

const person ={first: name
}

console.log(person);

const sayHelloLinting = (fName) => {
console.log(`Hello linting, ${fName}`)
}

sayHelloLinting('James');

If you’re familiar with code formatting, you may notice some missteps:

  • A mix of single and double quotes.
  • The first property of the person object should be on its line.
  • The console statement inside of the function should be indented.
  • You may or may not like the optional parenthesis surrounding the parameter of the arrow function.

Table of Contents

Prerequisites

To follow this tutorial, you need:

  • Download and install Visual Studio Code.
  • To work with Prettier in Visual Studio Code, you’ll need to install the extension. To do this, search for Prettier - Code Formatter in the extension panel of VS Code. If you’re installing it for the first time, you’ll see an install button instead of the uninstall button shown here:

Prettier extension readme

Step 1 — Using the Format Document Command

With the Prettier extension installed, you can now leverage it to format your code. To start, let’s explore using the Format Document command. This command will make your code more consistent with formatted spacing, line wrapping, and quotes.

To open the command palette, you can use COMMAND + SHIFT + P on macOS or CTRL + SHIFT + P on Windows.

In the command palette, search for format and then choose Format Document.

Command palette opened with results for format

You may then be prompted to choose which format to use. To do so, click the Configure button:

Prompt for selecting a default formatter

Then choose Prettier - Code Formatter.

Selecting Prettier

Note: If you do not see a prompt for selecting a default format, you can manually change this in your Settings. Set Editor: Default Formatter to esbenp.prettier-vscode.

Your code is now formatted with spacing, line wrapping, and consistent quotes:

const name = "James";

const person = { first: name };

console.log(person);

const sayHelloLinting = (fName) => {
  console.log(`Hello linting, ${fName}`);
};

sayHelloLinting("James");

This also works on CSS files. You can turn something with inconsistent indentation, braces, new lines, and semicolons into well-formatted code. For example:

body {color: red;
}
h1 {
  color: purple;
font-size: 24px
}

Will be reformatted as:

body {
  color: red;
}
h1 {
  color: purple;
  font-size: 24px;
}

Now that we’ve explored this command, let’s look at how this can be implemented to run automatically.

Step 2 — Formatting Code on Save

So far, you’ve had to run a command to format your code manually. To automate this process, you can choose a setting in VS Code to have your files automatically formatted when you save. This also ensures that code doesn’t get checked to version control that’s not formatted.

To change this setting, press COMMAND + , on macOS, or CTRL + , on Windows to open the Settings menu. Once the menu is open, search for Editor: Format On Save and make sure that option is checked:

Editor: Format On Save checked

Once this is set, you can write your code as usual and it will be automatically formatted when you save the file.

Step 3 — Changing the Prettier Configuration Settings

Prettier does a lot of things for you by default, but you can also customize the settings.

Open the Settings menu. Then, search for Prettier. This will bring up all of the settings that you can change:

Configuration Settings for Prettier

Here are a few of the most common settings:

  • Single Quote - Choose between single and double-quotes.
  • Semi - Choose whether or not to include semicolons at the end of lines.
  • Tab Width - Specify how many spaces you want a tab to insert.

The downside to using the built-in settings menu in VS Code is that it doesn’t ensure consistency across developers on your team.

Step 4 — Creating a Prettier Configuration File

If you change settings in your VS Code, someone else could have an entirely different configuration on their machine. You can establish consistent formatting across your team by creating a configuration file for your project.

Create a new file called .prettierrc.extension with one of the following extensions:

  • yml
  • yaml
  • json
  • js
  • toml

Here’s an example of a simple configuration file using JSON:

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

For more specifics on the configuration files, check out the Prettier Docs. After creating one of these and checking it into your project, you can ensure that every team member follows the same formatting rules.

Conclusion

Having consistent code is a good practice. It is particularly beneficial when working on a project with multiple collaborators. Agreeing upon a set of configurations helps with legibility and understanding of code. More time can be devoted to solving challenging technical problems instead of wrestling over solved problems like code indentation.

Prettier ensures consistency in your code formatting and makes the process automatic.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.