Search code examples
htmlvue.jseslintprettier

How to keep the </a> closing tag on same line and all the others in new line in a Vue.js project?


vue/html-closing-bracket-newline adds an unexpected space after the link text. removing the space creates a conflict and error in prettier and eslint. looking for a solution to over come this with a simple config change instead of a line by line ignore comment.

vue/html-closing-bracket-newline moves all the closing tags to new line, which adds an unexpected space after the link text

<a
 href="#"
 place="linkText"
 target="_blank">
lorum ipsum
</a>

link space


expected code syntax format is

<a
 href="#"
 place="linkText"
 target="_blank">lorum ipsum</a>

But it creates a conflict between prettier / eslint / vue.

prettier / eslint error

An easy solution would be adding <!-- eslint-disable-line --> in each anchor tag. But we are looking for a simple solution to cover all anchor tags in the project.


Solution

  • The issue is with the whitespace-sensitive formatting. This attribute htmlWhitespaceSensitivity accept the following options:

    • "css" - Respect the default value of CSS display property. For Handlebars treated same as strict. "Default"
    • "strict" - Whitespace (or the lack of it) around all tags is considered significant.
    • "ignore" - Whitespace (or the lack of it) around all tags is considered insignificant.

    You can fix it by adding the following rule to your .eslintrc.js file (rules section):

    "prettier/prettier": [
      "warn",
      {
        htmlWhitespaceSensitivity: "strict"
      }
    ]
    

    It would consider the whitespace "significant" for all cases. That means:

    <!-- input -->
    <span class="dolorum atque aspernatur">Est molestiae sunt facilis qui rem.</span>
    <div class="voluptatem architecto at">Architecto rerum architecto incidunt sint.</div>
    <div class="voluptatem architecto at">
      Architecto rerum architecto incidunt sint.</div>
    <div class="voluptatem architecto at">
      Architecto rerum architecto incidunt sint.
    </div>
    
    <!-- output -->
    <span class="dolorum atque aspernatur"
      >Est molestiae sunt facilis qui rem.</span
    >
    <div class="voluptatem architecto at"
      >Architecto rerum architecto incidunt sint.</div
    >
    <div class="voluptatem architecto at">
      Architecto rerum architecto incidunt sint.</div
    >
    <div class="voluptatem architecto at">
      Architecto rerum architecto incidunt sint.
    </div> <!-- in this case you would have the whitespace -->
    

    It looks ugly as it puts the </div at the end of the string and > the next line. But it solves the problem.

    You can read more about it here:
    https://prettier.io/blog/2018/11/07/1.15.0.html#whitespace-sensitive-formatting And here is an old Github issue on prettier stating the same as you mentioned here:
    https://github.com/prettier/prettier/issues/6290