Set up Prettier and VS Code to Format Your Code

How to set up Prettier and Visual Studio Code to format your code in less than a minute.

Published by Carlo Van September 8, 2023
Set up Prettier and VS Code to Format Code

Prettier is a code formatter that formats javascript, typescript, html and many other formats. 

In this tutorial, I'll show you how to set up prettier with VS Code so that documents are automatically formatted when you save a file.

Why Format Code?

  • Reduces the need to manually format code. For instance, breaking up long lines, setting indentation, indentation levels and so forth.
  • Ensure consistent formatting and style in your project, especially if there's multiple developers.
  • Make code easier to read

Step 1: Install the Prettier extension for VS Code

Install the prettier extension for VS Code here: https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode

Step 2: Create a .prettierrc file to specify formatting rules

Create a .prettierrc file and place it in the root of your project.

.prettierrc
{
  "semi": true,
  "trailingComma": "all",
  "singleQuote": true,
  "printWidth": 80,
  "endOfLine": "auto"
}

Step 3: Update VS Code Settings

Open the user settings JSON file by entering the keyboard shortcut CMD + Shift + P on Mac or Ctrl + Shift + P on Windows, then type in user settings, and select Preferences: Open User Settings (JSON).

Select Preferences: Open User Settings (JSON) from the Command Palette

Then add the following lines to the settings.json file and save it.

settings.json
{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode"
}

Step 4: Reload VS Code

Reload VS Code by entering the keyboard shortcut CMD + Shift + P on Mac or Ctrl + Shift + P on Windows, then type in reload, and select Developer: Reload Window.

Select Developer: Reload Window from the Command Palette

Step 5: Add npm Scripts to check and fix formatting (optional)

If you'd like to be able to run npm scripts to check and fix formatting for all your files in your project, do the following:

First, install prettier

shell
npm i prettier -D

Then, add the following in your package.json scripts section:

package.json
"scripts": {
    "prettier": "prettier --check '**/**/*.{js,jsx,ts,tsx,css}'",
    "prettier:fix": "prettier --write '**/**/*.{js,jsx,ts,tsx,css}'"
}

Modify the file extentions you'd like to check and fix with prettier accordingly.

Then, you can run npm run prettier in your pre-push git commit hook with a tool like husky to ensure that code is formatted correctly before pushing to your remote repository.

And if you encounter any formatting issues while running npm run prettier, you can automatically fix any formatting issues in your project by running npm run prettier:fix

Conclusion

That's how to set up Prettier in VS Code to format code when saving a file in less than 2 minutes.

Resources