Svelte - 101

Photo by Nik on Unsplash

Svelte - 101

Why Svelte

  • frontend framework

  • small bundle size

  • ease of use

  • inbuilt state management

  • animations and transitions (overrated framework is weak in this part, you know which framework! :D)

  • Overall fast

  • scoped styles + global styles

what is SvelteKit

a framework on top of Svelte for building full-fledged apps with built-in routing and other features , just like nextjs is build on react.js

conversation with svelte

Dheeraj : Hey svelte how you are so fast ?

$$Svelte : Well Dheeraj! I am compiler , i do all the compiling heavy lifting part for super devs like you so that you can easily focus on solving the problem

Dheeraj : wow! that's great, means svelte compile the components before its loaded on browser , NICE!! :D

Accha! Svelte can how give walkthrough of compilation process

$$Svelte - Sure why not

$$Svelte - let's go with simple counter app

// App.svelte

<script>
  let count = 0
  function incrementCount(){
    count += 1
  }
</script>


<p>{count}</p>
<button on:click={incrementCount}>Add</button>

My syntax is all about html and one can add script tag for state and variable part

<p>{count}</p>

this {} braces is called templating and wherever you see such braces assume that's my syntax and svelte territory starts

  • During compilation svelte parses the whole code and transform it to regular JavaScript

  • wherever i see templating I keep a track of that part , that means in future this value might change because its template

  • Also the thing which causes re-render of component is assignment , i look for assignment

  • in this case count is assignment , so during compilation i wrap such assignments with $$Invalidate function call()

$$invalidate(0,count) <--- wrapper , means marking this could change in future
this invalidate call will remount the component
and as a result my bundle size is less

So this is the secret of my energy , speed i means (no boost)

Okay nice meeting you all , now super dev will overtake

Dheeraj : thanks svelte that's really great explanation of inner working

So that's the super power of svelte also we can define styles in svelte component

// app.svelte

<script>
let greetings = "Hare Krishna"
</script>

<p>{greetings}</p>

<style>
   p{
      padding: 5px 10px;
    }
</style>

styles are scoped in svelte means it will only applied to this component, file and no mismatch with other elements and for global styles we can define styles in .css file

Wrapping up and hope you got a gist of svelte and will try out svelte soon

best