Use Prettier to Format VS Code to Enforce Consistent Style

2022/8/12 min read
bookmark this

Why need something like Prettier to format VS Code?

Code formatter might not as important as Lint or Test, which these are checking syntax or logic error, if something happen might introduce huge issue, but if you have lots developer working in the same codebase, each one has different style setting, or coding style which could cause the inconsistent style, and again nothing break but if you have consistent style through the entire codebase then you have less thing to worry about right?

What this article will provide

This article only consider how to use prettier extension at VS code, and provide below steps to make using prettier easier.

Install prettier package

First install the prettier as dev dependencies.

npm install --save-dev prettier

Add task script to the scripts section at package.json

After install the prettier and add this script task, this is for something might have some case want to update the entire solution. However, doesn't recommend to put this task as every build or use the husky during the commit or push command to the git, that'll will slow down the development due to search entire codebase and format code take sometime.

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

Add .prettierrc to the root

Add this file for the prettier setting for the current project.

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

Add .prettierignore to the root project

Add this so when run the prettier task so can exclude following folders.


Use VS Code Setting with Prettier to format code when save file

Create a folder .vscode and create settings.json, at the settings.json put the below content. This will use the prettier to format the code when try to save the file.

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


This article recommend to use prettier to format code, and use prettier with vscode extension so every time save the file will format the code, also incase need to run the prettier to the entire code base, so add the script task so can run as npm run prettier.