Fred Eric
Fred Eric

Reputation: 172

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.

Upvotes: 11

Views: 13933

Answers (1)

Subrato Pattanaik
Subrato Pattanaik

Reputation: 6049

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"

Upvotes: 6

Related Questions