Search code examples
javascripthtmlvue.jsprettier

Prettier force white space before and after every balise in HTML


I work on a project using Prettier, the project use Nuxt(Vuejs framework). I see a really weird behaviour about Prettier and the HTML rendered.


If i have a balise (h1,h2,div...) like this:

<h2>I am a too long title and i proc a error</h2>

Prettier want to format them like this:

<h2>
  I am a too long title and i proc a error
</h2>

There is no problem and i like to have this format, but when i inspect the element inside the browser inspector i can see a white space before and after the text.

<h2> I am a too long title and i proc a error </h2>

This is really unexepected, and really bad too, the only way to solve this i have fund is to not format it with prettier. But i can't believe this problem is on every project in all world who use Prettier.

https://codepen.io/deeluxe/pen/dyqXZMj -> example with space before and after on the second element.


Solution

  • I added already a comment, but I want to also post it as an answer here, because someone else might also have the same question at some point.

    In the prettier options you can configure the htmlWhitespaceSensitivity which can have different values. This setting is also used in Vue templates to format the HTML.

    The htmlWhitespaceSensitivity option can have three values:

    strict

    Strict sensitivity makes sure, that the whitespace characters within the element are not changed. (If this looks good, is another question)

    <h2
      >I am a too long title and i proc a error</h2
    >
    

    ignore

    Prettier would add whitespace if it is needed for the formatting.

    <h2>
      I am a too long title and i proc a error
    </h2>
    

    css

    Respect the default whitespace character handling of html elements.

    <h2>
      I am a too long title and i proc a error
    </h2>
    
    <!-- inside a pre element: -->
    <pre>
    I am a too long title and i proc a error</pre
    >