Svelte - Technological watch

Learn what is Svelte in less than 5 minutes !
Tuesday, January 23, 2024

Introduction

Svelte, a JavaScript framework for constructing UI components, operates similarly to React, Angular, or Vue. However, it distinguishes itself by functioning as a compiler rather than relying on a Virtual DOM like its counterparts.

In essence, Svelte transpiles declarative code into JavaScript that seamlessly integrates with web browsers. The result is a generation of high-performance code delivered in a compact package.

How it works

To create a Svelte component, you need to create a .svelte file like this.

And of course you can use Typescript or SASS with it.

MyCounter.svelte
<script lang="ts">
let count: number = 0;
function increment() {
count += 1; // Automatic re-render
}
</script>
<button on:click={increment}>
Clicked {count} times
</button>
<style lang="scss">
button {
background-color: orange;
color: black;
}
</style>

You can use conditional rendering, loops, and other stuff !

  1. Conditional rendering:
IfElseDemo.svelte
<script>
let x = 7;
</script>
{#if x > 10}
<p>{x} is greater than 10</p>
{:else if 5 > x}
<p>{x} is less than 5</p>
{:else}
<p>{x} is between 5 and 10</p>
{/if}
  1. Loops:
LoopDemo.svelte
{#each ["Alex", "Hugo", "Lucas"] as name}
<p>Hello {name}</p>
{/each}
  1. Await:
PromiseDemo.svelte
{#await promise}
<p>...waiting</p>
{:then number}
<p>The number is {number}</p>
{:catch error}
<p style="color: red">{error.message}</p>
{/await}

Using components

You can create a component, and use it:

Hello.svelte
<script lang="ts">
export let name: string;
</script>
<div>Hello {name} !</div>

And then use this component like this:

Page.svelte
<Hello name="Vincent" />
<!-- Displays: <div>Hello Vincent !</div> -->

(Demo here: https://svelte.dev/examples/declaring-props)

Stores

You can save global variables in Svelte stores.

StoreDemo.svelte
<script>
import { writable } from 'svelte/store'
const theme = writable<"light" | "dark">("dark");
</script>
<div>The global theme is: {$theme}</div>

$ means “subscribe” to a store. If the value changes, the component re-renders.

(doc: https://svelte.dev/docs/svelte-store)

Advantages

  1. Easy to write code, Svelte is logical. Less code = less problems. 💡
  2. Svelte is lightweight. 🌠
  3. Svelte is performant, no VirtualDOM to care about ! The output code works well on smaller configuration. No need to import a BIG library like React or Vue to load the interface. 🚀⚡

Disadvantages

  1. The community is smaller. There is a smaller open-source ecosystem. But Svelte popularity is growing up every year. (https://2022.stateofjs.com/en-US/libraries/)
  2. Svelte is an abstraction of Javascript. You won’t play with .js files. So you need to download extensions and setup the project before using.
  3. Not too much Job opportunities with Svelte yet.

Recommended articles