Skip to main content

Format Code with Prettier in Visual Studio Code

While working with a team formatting code in a consistent style is a big challenge unless your IDE or tool is doing it. Today we are gonna use one of such tool called Prettier which support JavaScript, TypeScript, HTML, JSON or many other technologies.

It is pretty good tool which format your code whenever you save your code. Follow below steps to integrate it with VS Code:

Step 1: To install prettier using NPM you can type below command in VS terminal:

npm install --save-dev --save-exact prettier

Step 2: Install Prettier Extension. Click on Extension Icon. Search for Prettier and click on install.

extension icon in visual studio code 

Step 3: Open Settings, search with formatter text and set Editor: Default Formatter to Prettier - Code formatter

visual studio code set formatter to default option

Step 4: Search for prettier in settings, select Require a prettier configuration file to format from Prettier: Require Config

set require config for prettier visual studio

Step 5: Search for format on save in settings, and select Format a file on save. from Editor: Format on Save

select format on save

Step 6: Create file .prettierrc in your project root directory and add following basic configuration. Detail configuration you can get it from here

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

Step 7: Create file .prettierignore in your project root directory and add files which you do not want to format.

# Ignore artifacts:
build
coverage

# Ignore all HTML files:
*.html

That's all now whenever you save your file. It will format according to .prettierrc file options. 

Submitted by tgoswami on November 26, 2021

Tarun has 11+ years of experience in Quality Assurance in different domains like Banking, E-commerce, Health and Education.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.