Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird HTML formatting with prettier

I have this HTML when I use the built-in formatter. Not good. I want every tag to be cascaded. Here, we have span and svg and a on same line.

enter image description here

After formatting with prettier (this version)

I get this. This is almost worse. (see edit section later that explains why it’s actually a smart choice from prettier.)

enter image description here

Prettier config is

enter image description here

What can I use to properly auto format this HTML ?


Edit: I got what I want with the Beautify extension and editing its inline config. enter image description here

Here is why prettier is formatting like this. It is a workaround to not break content display. Actually, it is pretty smart once you get used to it.

You can override it with the option

"prettier.htmlWhitespaceSensitivity": "ignore",

See the link above to know more about this.

like image 894
Fred Eric Avatar asked Jan 01 '21 11:01

Fred Eric


People also ask

Can prettier format HTML?

Languages supported by Prettier: JavaScript, TypeScript, JSX, Angular, Vue, CSS, HTML, JSON, GraphQL, and much more.

How do I beautify HTML Orcode?

To improve the formatting of your HTML source code, you can use the Format Document command Ctrl+Shift+I to format the entire file or Format Selection Ctrl+K Ctrl+F to just format the selected text. The HTML formatter is based on js-beautify.

How do you code vs prettify?

VSCode – Code Formatting Shortcuts The code formatting is available in Visual Studio Code (VSCode) through the following shortcuts or key combinations: On Windows Shift + Alt + F. On macOS Shift + Option + F. On Linux Ctrl + Shift + I.


1 Answers

You can set a prettier format as the default format for your editor to all programming languages by putting prettier properties in the setting.json file.

"editor.defaultFormatter": "esbenp.prettier-vscode",

Prettier format for HTML doesn't look so cool in my opinion so I have set it to default VS Code format.

"[html]": {
    "editor.defaultFormatter": "vscode.html-language-features"
},

If you want the Beautify format extension to your HTML you can install the beautify extension and add this line in the setting.json file

"[html]": {
    "editor.defaultFormatter": "HookyQR.beautify"
}

Similarly, you can set a different format extension to a different language. In my opinion, this is the standard way of setting the format extension to one or many languages.

You can do it like this

"beautify.language": {
    "html": ["html", "php", "erb"],
},

Edited

All credits to @Fred.

You can achieve the same behavior of beautify extension in prettier by the following property.

"prettier.htmlWhitespaceSensitivity": "ignore"
like image 196
Subrato Pattanaik Avatar answered Oct 21 '22 15:10

Subrato Pattanaik