Skip to content
doubtly

1 answer

Best answer

Answer: Svelte is a compiler, not a runtime framework. At build time it converts your components into small, plain JavaScript modules that update the real DOM directly, so no virtual DOM or diffing library is shipped to the browser.

How it works:

  1. Write components: Each component is a .svelte file containing three optional parts: a <script> block (state and logic), HTML-like markup (the template) and a <style> block (CSS).
  2. Compile at build time: The Svelte compiler (used through tools such as Vite/SvelteKit, Rollup or webpack plugins) reads every component and analyses which variables are used in which parts of the markup.
  3. Generate direct DOM code: For each component it outputs JavaScript that creates the DOM nodes once and contains exact update instructions, for example "when count changes, set the text of this one node". There is no virtual DOM and no comparison of old and new trees at run time.
  4. Reactivity by assignment: A plain assignment such as count = count + 1 is enough. The compiler marks that variable as changed and schedules only the affected DOM updates. Statements written with $: (Svelte 3/4) or runes like $state and $derived (Svelte 5) are recalculated when their inputs change.
  5. Scoped CSS: Styles in a component are scoped automatically by adding a unique class, so they do not leak into other components; unused CSS is removed.
  6. Small, fast output: Because the "framework" work is done by the compiler, the browser receives a small bundle with very little runtime code, which loads and runs quickly.

Example (Counter.svelte):

<script>
  let count = 0;
  function increment() {
    count = count + 1;   // assignment triggers the update
  }
</script>

<button on:click={increment}>
  Clicked {count} times
</button>

<style>
  button { padding: 8px 16px; }
</style>

main.js:

import Counter from './Counter.svelte';

const app = new Counter({
  target: document.getElementById('app')
});

Result: the page shows a button "Clicked 0 times"; each click changes only the number inside that button's text node.

codelikepro · 21 Aug 2022 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.