Detailed Explanation of the Concepts and Usage of Svelte Special Tags and Directives

In Svelte, besides regular HTML tags and component tags, there are special tags and directives that provide additional functionalities for handling the head, dynamic component loading, global event listening, and more. This article will introduce common special tags and directives in Svelte and their usage in detail.

<svelte:head>

The <svelte:head> tag is used to dynamically modify the document’s head information, such as the title (<title>) and meta tags (<meta>) in a component. Only one <svelte:head> tag is allowed in a Svelte component, and it is typically used with Svelte lifecycle hooks.

Example Code

1
<script>
2
import { onMount } from "svelte";
3
4
onMount(() => {
5
document.querySelector("title").innerText = "Dynamic Title";
6
});
7
</script>
8
9
<svelte:head>
10
<title>Hello Svelte!</title>
11
<meta
12
name="description"
13
content="This is a demo of using Svelte's special tags and directives."
14
/>
15
</svelte:head>

In this example, the <svelte:head> tag is used to set the document’s title and description. The title is dynamically modified in the onMount lifecycle hook.

<svelte:component>

The <svelte:component> tag is used for dynamically loading and rendering Svelte components. It allows for the selective loading of different components at runtime, enabling dynamic component switching.

Example Code

1
<script>
2
import FirstComponent from "./FirstComponent.svelte";
3
import SecondComponent from "./SecondComponent.svelte";
4
5
let showFirst = true;
6
7
function toggleComponent() {
8
showFirst = !showFirst;
9
}
10
</script>
11
12
<button on:click={toggleComponent}>Toggle Component</button>
13
14
<svelte:component this={showFirst ? FirstComponent : SecondComponent} />

In this example, either FirstComponent or SecondComponent is dynamically rendered based on the value of showFirst.

<svelte:window>

The <svelte:window> tag is used to listen for and handle global window events such as resize and scroll within a component.

Example Code

1
<script>
2
function handleResize() {
3
console.log("Window resized!");
4
}
5
</script>
6
7
<svelte:window on:resize={handleResize} />

In this example, the handleResize function is triggered when the window is resized.

<svelte:body>

The <svelte:body> tag is used to dynamically modify the document’s body (<body>) part within a component, useful for dynamically adding global styles or JavaScript.

Example Code

1
<svelte:body>
2
<script>
3
console.log('This script will be inserted into the document body.');
4
</script>
5
</svelte:body>

In this example, the code inside the <script> tag will be inserted into the document’s <body>.

<svelte:self>

The <svelte:self> tag is used for recursively referencing the component itself, enabling recursive structures.

Example Code

1
<script>
2
let count = 0;
3
4
function increment() {
5
count += 1;
6
}
7
</script>
8
9
<button on:click={increment}>Increment</button>
10
11
{#if count < 5}
12
<svelte:self />
13
{/if}
14
15
<p>Count: {count}</p>

In this example, a simple counter is implemented using a recursive self-reference until the counter value is less than 5.

Directives: @html, @const, @debug

Besides special tags, Svelte also provides useful directives for controlling rendering behavior, optimizing performance, and more.

@html Directive

The @html directive is used to render strings containing HTML code, bypassing Svelte’s default HTML escaping and directly inserting the string as HTML into the document.

Example Code

1
<script>
2
let htmlContent = "<strong>Hello Svelte!</strong>";
3
</script>
4
5
{@html htmlContent}

In this example, the content of htmlContent is inserted as HTML into the document, displaying “Hello Svelte!” in bold.

@const Directive

The @const directive is used to declare constants, helping Svelte optimize during compilation and reduce runtime computation overhead.

Example Code

1
<script>
2
export let boxes;
3
</script>
4
5
{#each boxes as box}
6
{@const area = box.width * box.height}
7
{box.width} * {box.height} = {area}
8
{/each}

In this example, @const defines a local constant. The {@const} directive can only be a direct child of {#if}, {:else if}, {:else}, {#each}, {:then}, {:catch}, <Component />, or <svelte:fragment />.

@debug Directive

The @debug directive is used for debugging and outputting the values of variables to the console, typically used during development for debugging code.

Example Code

1
<script>
2
let user = {
3
firstname: "Ada",
4
lastname: "Lovelace",
5
};
6
</script>
7
8
<!-- Compiles -->
9
{@debug user}
10
{@debug user1, user2, user3}
11
12
<!-- WON'T compile -->
13
{@debug user.firstname}
14
{@debug myArray[0]}
15
{@debug !isReady}
16
{@debug typeof user === 'object'}
17
18
<h1>Hello {user.firstname}!</h1>

The {@debug ...} tag provides an alternative to console.log(...). It logs specific variable values and pauses code execution when the dev tools are open if those values change.

The {@debug ...} directive accepts a comma-separated list of variable names (not arbitrary expressions).

Summary

In this article, we have introduced the concepts and usage of common special tags and directives in Svelte. These special tags and directives provide more flexibility and functionality in Svelte, allowing better handling of dynamic content, global events, component recursion, and optimizing rendering behavior during development.