This chapter covers tips for debugging Svelte applications. These include:
- Using the
@debugtag
- Using reactive statements for debugging
- Using svelte-devtools
There are three popular ways to debug issues in Svelte applications.
The most basic approach is to add @debug tags that pause execution and output variable values. Another approach is to use reactive statements to output the values of JavaScript expressions any time variables they use change. Both of these use features built into Svelte.
A final approach covered here is to use a browser extension to view the component hierarchy. After selecting a component, its props and state can be viewed and modified.
We use the @debug tag to pause execution (break) when given top-level variables change and output their values in the browser devtools console. The browser debugger can then be used to examine the code and other variables that are in scope.
To do this, place the @debug tag at the top of the HTML section, not inside a <script> tag. For example, here is a Svelte component that allows the user to enter the radius of a circle and computes its area. We want to break any time the value of radius or area changes.
Listing 11.1. App.svelte
<script>
export let radius = 1;
$: area = 2 * Math.PI * radius**2;
</script>
{@debug radius, area}
<main>
<label>
Circle Radius:
<input type="number" bind:value={radius}>
</label>
<label>
Circle Area: {area}
</label>
</main>