You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
svelte/documentation/docs/02-runes/07-$inspect.md

2.5 KiB

title
$inspect

[!NOTE] $inspect only works during development. In a production build it becomes a noop.

The $inspect rune is roughly equivalent to console.log, with the exception that it will re-run whenever its argument changes. $inspect tracks reactive state deeply, meaning that updating something inside an object or array using fine-grained reactivity will cause it to re-fire (demo):

<script>
	let count = $state(0);
	let message = $state('hello');

	$inspect(count, message); // will console.log when `count` or `message` change
</script>

<button onclick={() => count++}>Increment</button>
<input bind:value={message} />

$inspect(...).with

$inspect returns a property with, which you can invoke with a callback, which will then be invoked instead of console.log. The first argument to the callback is either "init" or "update"; subsequent arguments are the values passed to $inspect (demo):

<script>
	let count = $state(0);

	$inspect(count).with((type, count) => {
		if (type === 'update') {
			debugger; // or `console.trace`, or whatever you want
		}
	});
</script>

<button onclick={() => count++}>Increment</button>

A convenient way to find the origin of some change is to pass console.trace to with:

// @errors: 2304
$inspect(stuff).with(console.trace);

$inspect.trace(...)

This rune, added in 5.14, causes the surrounding function to be traced in development. Any time the function re-runs as part of an effect or a derived, information will be printed to the console about which pieces of reactive state caused the effect to fire.

<script>
	import { doSomeWork } from './elsewhere';

	$effect(() => {
		+++$inspect.trace();+++
		doSomeWork();
	});
</script>

$inspect.trace takes an optional first argument which will be used as the label.