How to add comments in Svelte templates
By Flavio Copes
Learn how to add comments in Svelte templates and why, unlike plain HTML comments, Svelte strips them out completely so they never reach the browser.
To add a comment in a Svelte template, you use the regular HTML comment syntax. The nice part is that Svelte strips them out at compile time, so they never reach the browser.
Let’s start from plain HTML. HTML comments are great to hide elements from a page.
In HTML here’s how you add a comment:
<!-- a comment here -->
You can use this on blocks, too, to hide multiple lines of HTML:
<!--
a
comment
here
-->
Note that in plain HTML this is still visible in the page source. The browser just hides it, but one can always go and see the comment.
You can use the same comments in your Svelte templates. But with Svelte you don’t send the commented part to the browser. That part is completely removed, and only stays in your source files, invisible to the HTML generated into the page.
Which in my opinion is a positive thing. Notes you write for yourself, or half-finished markup you commented out, stay private.
What about the script and style blocks?
HTML comments only work in the markup part of a component. Inside the script block you use JavaScript comments:
<script>
// the count starts at zero
let count = 0
</script>
Inside the style block you use CSS comments:
<style>
/* keep in sync with the header height */
main {
padding-top: 60px;
}
</style>
Mixing them up is a common mistake. An HTML comment inside the script block is a syntax error, and // inside the markup is just printed as text.
Special comments the compiler reads
Svelte gives comments one extra job. A comment starting with svelte-ignore silences a compiler warning on the element right below it:
<!-- svelte-ignore a11y-autofocus -->
<input autofocus />
Use it when you’ve looked at the warning and decided it doesn’t apply to your case, not as a way to mute everything.
One thing to watch out for
HTML comments don’t nest. If the markup you’re commenting out already contains a comment, the outer comment ends at the first --> it finds, and everything after that comes back to life.
If that happens, remove the inner comment first, or comment out the pieces separately.