This content originally appeared on remy sharp's b:log and was authored by remy sharp's b:log
A simple but effective fix to working with web components and VS Code. I wanted to get syntax highlighting and prettier support (to auto fix indenting, quotes, etc) in my component's templates.
The extremely quick read is, add /* HTML */ to the front of the template. Case sensitive and space sensitive (though hopefully one day it won't be so strict). Now highlighting and prettier (with save and fix) works.
The slightly longer read
What I wanted to achieve was that I could include my template in the source of the web component (or at least in the same directory - i.e. physically near to the application logic).
The problem is that unless I use a build function (or tools), the markup for the template is a string.
Here's the starting point:
customElements.define(
'hello-world',
class extends HTMLElement {
connectedCallback() {
const n = this.getAttribute('name') || 'World';
this.attachShadow({ mode: 'open' }).innerHTML = `
<style>:host{font:600 16px system-ui;color:#222}</style>
<div>Hello, ${n} 👋</div>`;
}
}
);
Seen here with VS Code's syntax highlighting - note that the template itself is just green, plain text:

Using a tag function solves the main issue, but requires extra code or a magic build process which I really don't want or need - and look at that nasty red snake telling me I need to write more code:

VS Code does support highlighting if you give it a hint using a comment: /*html*/, but prettier doesn't format it - close, but still no dice:

Finally, if you get the comment syntax exactly right, that's uppercase and with spaces around the text, /* HTML */, then you'll get both highlighting and syntax tidy support without the need for build tools:

I do have the VS Code option "prettier.embeddedLanguageFormatting": "auto" in my settings, but if I've understood correctly, this should be the default for prettier and not required.
A large hat tip to Timothy Leverett on Mastodon for helping me.
Originally published on Remy Sharp's b:log
This content originally appeared on remy sharp's b:log and was authored by remy sharp's b:log
remy sharp's b:log | Sciencx (2025-11-12T00:00:00+00:00) Syntax Highlighting in Web Component Templates [blog]. Retrieved from https://www.scien.cx/2025/11/12/syntax-highlighting-in-web-component-templates-blog/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.