Hyston blog
About • RSS

Svelte

2022-01-03 18:24

Most of current frontend frameworks are build upon making virtual DOM. All UI changes are applied to this structure, then it is getting compared to real DOM and only then framework adjust actual page. Just before Christmas, when there were not a lot of stuff to do, one collegue mentioned to me Svelte framework, that use different approach and I decided to give it a try.
TLDR: using virtual DOM is slow; All changes can be made manually, and code can be generated in compile-time. Svelte moves complexity from client browser realtime into dev machine compile time.
All code is written in html-like files with .svelte extension. On building (svelte-kit build) all code in <script> get compiled into javascript, <style> goes into css. I have not made any real comparisons with big projects, but for small hello worlds it loads really fast and generates a lot of "compiled" javascript code that became unreadable really fast.
For me, actually, the biggest benefit was a flat learning curve. This is component-based framework, that is really start with. I'm using react lately and I find that there are too much conventional boilerplate code. For example, here is hello-click-me-world example in svelte:

<script>
	let count = 0;

	function handleClick() {
		count += 1;
	}
</script>

<button on:click={handleClick}>
	Clicked {count} {count === 1 ? 'time' : 'times'}
</button>

Html can be enchanced with conditional statements and loops:

{#each values as value}
	<li>{value}</li>
{/each}

Input elements can be binded by attributes bind:value. Even regular variables can be "reactified" by adding $: before declaration.

<script>
	let count = 0;
	$: double = count * 2;
</script>

<button on:click={e => count += 1}>Click</button>
<p>{count}</p>
<p>{double}</p>

In this example after clicking button second label would not be updated without $: statement. As I understood, first label is getting updated anyway because it is already used in handler.
DOM gets updated on each assignment operator, not by anything else. So, if you need to update array, then use spread syntax: values = [...values, { name: newName }];

I think it is a nice framework to play around with, very easy to start, however, it's conventions were broken by moving to each major version and it's unclear (as with every new js-framework) how popular would it be and how many support will it get. May be it can be used for small dev-related project, where react or angular would be overkill.
And for my purposes I'll continue to explore react in my free time, since this seems to be the most popular frontend. Although typescript is very painfull and unfriendly after years of writing in C#.1


← Prev entry