Skip to content

Svelte tutorial#

See svelte

The new tutorial for Svelte 3. Interactive.

Components#

A Svelte application is composed from one or more components. A component encapsulated HTML, CSS and JS in a .svelte file. It can be one or more of these.

  1. JS - JS wrapped in a <script> tag
  2. HTML - mark up apparently not wrapped with anything

    • Can embed and execute JS using braces
    • HTML attributes can be set with " but also if named correct <img {src}>
    • {@html } tells Svelte to insert HTML into the DOM (by default treated as string)
    • {#if } and {:else} are used for conditional rendering
    • CSS - CSS wrapped in <style> tag

Components can be imported and used as tags

Code structure#

Building#

Svelte for new developers

Vite and the vite-plugin-svelte is recommended build tool. SvelteKit is the under development application framework from the Svelte team.

npm create vite@latest my-app -- --template svelte

Reactivity#

  • Reactivity is triggered by assignment statements
  • Variables displayed in HTML are auto updated as JS changes values
  • To chain variables (i.e. have a 2nd variable also update based on changes in first) precede any linkage with $:
  • $: can be wraped around JS code so it is run reactively

Sharing state between components#

  • Internal state - values only accessible within the component
  • properties are declared to pass data to a component's children
  • These can be set as an attribute in the component tag
  • object of properties can be spread