Edgar Derby
Edgar Derby

Reputation: 2825

Visual Studio Code: How to automatically format HTML contained in template literals?

In my Javascript code I have many template literals that contain HTML code. These blocks are correctly highlighted via es6-string-html. However, they are not formatted automatically, which means the following block will be left as is:

let html = `
      <div class="wrapper">
<div>Hello, world!
     </div>
                 </div>
      `;

How can I enable auto-formatting for these strings as well?

Upvotes: 12

Views: 6000

Answers (2)

Vidar
Vidar

Reputation: 1238

You can use a comment in front of your template string to tell Prettier that it's HTML:

function component() {
  return /* HTML */ `<div>hello</div>`
}

or use a function like Chris said:

function component() {
  return html`<div>hello</div>`
}

Upvotes: 4

Chris
Chris

Reputation: 2397

When Prettier detects a tagged template in JavaScript with a tag named html, it will format it. You can read more about this here and for highlighted you can use what you suggested es6-string-html

/**
 * html wrapper is needed for prettier formatting
 */
const html = String.raw;

const template = html`
  <div>
    <p>hello world</p>
    <p>hello world</p>
  </div>
`;

Upvotes: 14

Related Questions