Use Prettier to Format VS Code to Enforce Consistent Style

2022/08/013 min read
bookmark this
Responsive image

Table of Contents

  1. Introduction
  2. Why Need Something Like Prettier to Format VS Code?
  3. What This Article Will Provide
  4. Install Prettier Package
  5. Use VS Code Setting with Prettier to Format Code on Save
  6. Conclusion

Introduction

This article covers how to use Prettier with VS Code to enforce consistent code formatting style across your project, including installation, configuration, and VS Code integration.

Why Need Something Like Prettier to Format VS Code?

A code formatter might not be as important as Lint or Test, which check for syntax or logic errors that could introduce huge issues. But if you have many developers working in the same codebase, each one with different style settings or coding styles, it could cause inconsistent formatting. Again, nothing breaks, but if you have a consistent style throughout the entire codebase, then you have one less thing to worry about, right?

What This Article Will Provide

This article only covers how to use the Prettier extension in VS Code and provides the steps below to make using Prettier easier.

Install Prettier Package

Install Prettier as a Dev Dependency

npm install --save-dev prettier

Add Task Script to the Scripts Section in package.json

After installing Prettier, add this script task. This is for cases where you might want to format the entire solution. However, it's not recommended to run this task on every build or use Husky during the commit or push command to Git, as that will slow down development due to searching the entire codebase and formatting code taking some time.

"scripts": {
    "prettier": "prettier --write ."
}

Add .prettierrc to the Root

Add this file for the Prettier settings for the current project.

{
  "trailingComma": "es5",
  "tabWidth": 2,
  "semi": true,
  "singleQuote": true
}

Add .prettierignore to the Root Project

Add this file so that when running the Prettier task, it can exclude the following folders.

.next
dist
node_modules
output

Use VS Code Setting with Prettier to Format Code on Save

Create a folder .vscode and create settings.json. In the settings.json, put the content below. This will use Prettier to format the code when you save the file.

{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll": true,
    "source.organizeImports": true
  }
}

Conclusion

This article recommends using Prettier to format code and using the Prettier VS Code extension so that every time you save a file, the code is automatically formatted. In case you need to run Prettier on the entire codebase, add the script task so you can run it as npm run prettier.