Search code examples
sveltesvelte-3

How to change variable value in Svelte app via browser's console


Could you please explain how can I see reactivity in Svelte app. So if I change variable value in browser's console I would see updated DOM. If I have App.svelte file below, is it possible to assign new value to "name" variable in browser's console and see update "h1" element instantly?

<script>
let name = 'world';
</script>

<h1>Hello world!</h1>

<h1>Hello {name}!</h1>

Solution

  • This is not directly possible with Svelte. The reason for this is because those variables do not exists on the global scope of your document, they are encapsulated by the browser into the app and shielded from outside interference.

    One way around this would be to explicitly define a way to do this

    <script>
        let name = 'world';
        
        window.setName = (val) => name = val;
    </script>
    
    <h1>Hello {name}!</h1>
    

    Now you can do window.setName('test') in the console and it will change the value of name