An introduction to Svelte

Why bother learning a new framework ?

It lets you better understand and critically assess the API choices of other frameworks

React might not be around forever

also Facebook is evil

Some background on Svelte

Rich Harris

V3 released in April 2019

What makes Svelte unique

Compiler framework

🤯

{
  "dependencies": {} 
}

Performance

4KB (min + gzip) for a "hello world" app

no virtual DOM

Simplicity

<script>
	let a = 1;
	let b = 2;
</script>

<input type="number" bind:value={a}>
<input type="number" bind:value={b}>

<p>{a} + {b} = {a + b}</p>
import React, { useState } from 'react';

export default () => {
  const [a, setA] = useState(1);
  const [b, setB] = useState(2);

  function handleChangeA(event) {
    setA(+event.target.value);
  }

  function handleChangeB(event) {
    setB(+event.target.value);
  }

  return (
    <div>
      <input type="number" value={a} onChange={handleChangeA}/>
      <input type="number" value={b} onChange={handleChangeB}/>

      <p>{a} + {b} = {a + b}</p>
    </div>
  );
};
<template>
  <div>
    <input type="number" v-model.number="a">
    <input type="number" v-model.number="b">

    <p>{{a}} + {{b}} = {{a + b}}</p>
  </div>
</template>

<script>
  export default {
    data: function() {
      return {
        a: 1,
        b: 2
      };
    }
  };
</script>

Svelte

React (w/ hooks)

Vue

"True" reactivity

var a = 10;
var b = a + 1;
a = 11;
b = a + 1;

Example from Paul Stovell's What is reactive programming ?

var a = 10;
$: b = a + 1;
a = 20;
console.log(b); // 21
var a = 10;
var b <= a + 1;
a = 20;
console.log(b); // 21

Making a statement reactive

Other specificities of Svelte

Single file components

"Props" system similar to React

<script>
	export let foo;

	// Values that are passed in as props
	// are immediately available
	console.log({ foo });
</script>

You can also "dispatch" custom events up the component tree but general data-flow is top -> down

Scoped CSS out of the box

Bonus : unused selectors are not shipped to the browser !

Some basic templating logic for conditional rendering, looping over iterables in your html

Two-way data bindings on form elements

Built-in centralized store system

Limitations

(aka why don't we refactor all Keytrade web apps to Svelte)

Lack of maturity / stability

Small ecosystem

Sapper

Svelte Native

DSL aka templating language (disclaimer : I really like JSX)

Reactivity through assignments takes a little time to get your head around

e.g. array methods like .push() and .splice() won't automatically trigger updates !

Try it out !

An introduction to Svelte

By maelig

An introduction to Svelte

  • 1,635