Wanna see something cool? Check out Angular Spotify 🎧

Prettier - prevent HTML closing tag > being placed on a new line?

Problem

Our project uses Prettier to format our code. We have Angular components that have HTML code in them.

Prettier formats the HTML code in the Angular component and places the closing tag > on a new line. This is not what we want.

<label class="mb-10 flex">
  <span>
    I accept the
    <a class="underline" routerLink="/tnc"
      >Our terms and conditions</a
    >
  </span>
</label>

The reason is because Prettier is trying to preserve the whitespace between the a tag and the closing tag >. Thus, it places text like >Our terms and conditions< so that the whitespace is preserved.

See the explanation from the Prettier documentation:

Solution

Since we are not interested in preserving the whitespace between HTML tag, we can tell Prettier to ignore the whitespace sensitivity by updating Prettier configuration file with htmlWhitespaceSensitivity option to ignore.

module.exports = {
  bracketSameLine: true,
  trailingComma: 'all',
  tabWidth: 2,
  semi: true,
  singleQuote: true,
+  htmlWhitespaceSensitivity: 'ignore',
};

Now run prettier again for all html files, the closing tag > should be on the same line as the last attribute.

npx prettier "**/*.html" --write --ignore-unknown
<label class="mb-10 flex">
  <span>
    I accept the
    <a class="underline" routerLink="/tnc">
      Our terms and conditions
    </a>
  </span>
</label>

References

Published 1 Feb 2023

    Read more

     — zsh history not working after VSCode upgrade
     — The different between :focus and :focus-visible
     — Angular 13 upgrade - Error: Unknown keyword formatMinimum
     — ngIf - Store the conditional result in a variable
     — Common use cases and solutions for accessibility in Angular

    Follow @trungvose on Twitter for more!