Today, we will explore another Visual Studio code extension Prettier that helps you to auto-format the code in Visual Studio Code.
What is Prettier?
Prettier is a simple code format that automatically formats your code when saving the source file and automatically adds the missing semicolon in your code.
Features:
- Helping beginners to easily format their own code.
- If you forget to put spaces in the wrong places, the Prettier will ignore them.
- It makes your source code readable.
- It also reduces the time that you take in making a format for a file.
Supported language
- JavaScript (including experimental features)
- JSX
- Angular
- Vue
- Flow
- TypeScript
- CSS, Less, and SCSS
- HTML
- JSON
- GraphQL
- Markdown, including GFM and MDX
- YAML
How to Install the Prettier extension for Visual Studio Code?
To install the Prettier extension for Visual Studio Code, you should follow the below steps:
Steps
- Go to the extension button, and search for prettier, then click install.
- After the installation is finished, you will notice that the extension has been enabled globally as below.
How to use the Prettier extension for Visual Studio Code?
To can use the Prettier, you should first create an empty config file to let the editor know you are using Prettier and type {}
Note: the config file will apply the auto-format for all supported languages. Howerver, you can create a .prettierignore file to let the Prettier know which language you need tp ignore!
EX: if you added the below code, so the prettier will be applied for all lanugaue expect JS.
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[javascript]": {
"editor.defaultFormatter": null
}
}
How to adjust Prettier extension settings in Visual Studio code?
- Click on the setting gear icon, and then click on Settings, and then search for Prettier.
- Now, you can see the related settings for the Prettier extension and you can set it as you prefer!
1) Bracket spacing
When you enable this setting will print spaces between brackets
For example, this setting helps you format the below code to a readable format
{ foo: bar;}
After saving your file, the code will be formatted in a readable format as below
{
foo: bar;
}
2) Require config
Uncheck this checkbox to let the editor apply formatting without using Confi file.
3) Single Quote
Enable checkbox if you want to use single quotes instead of double quotes
4) Formatter
There are also other settings you have to adjust it as the following:
In the Settings search box, type Formatter
- Default formatter: From the dropdown list, select prettier-code formatted.
- "Format on save" to apply the format when you save your file.
Simple example
Below is an example for a code that not formatted where you are missing a semicolon and there are unneeded spaces!
After you save your file, it will be formatted and adding a semicolon automatically.
Learn More
This video shows how you can Prettier format your JavaScript code
See also