Few weeks ago I came across Svelte, a radical new approach to building user interfaces (quote from Svelte homepage). Svelte is actually a compiler, not tradional framework like React, Angular or Vue, but it can do pretty much everything as the mentioned ones. It doesn’t use virtual DOM, but instead it compiles to vanilla JavaScript and access the DOM directly. As a consequence, Svelte generated JavaScript is very small comparing to competition, but also quite fast.
But the best think about Svelte is it’s syntax. It looks so easy but in the same time powerful that it intrigued even me as a backend developer. Within few minutes I decided to start learning it and try something new. I had lot of fun since.
Here is a piece of Svelte code (component) to illustrate the simplicity and power:
<script>
async function fetchData() {
const res = await fetch("https://jsonplaceholder.typicode.com/todos");
const data = await res.json();
if (res.ok) {
return data;
} else {
throw new Error(data);
}
}
</script>
{#await fetchData()}
<p>loading</p>
{:then items}
{#each items as item}
<li>{item.id}. {item.title}</li>
{/each}
{:catch error}
<p style="color: red">{error.message}</p>
{/await}
The code lying in the script tag is just ES6 JavaScript, but the await block beneath is a syntactic sugar from Svelte. So, instead of handling await in plain JavaScript, you can actually handle it in Svelte’s await block. While waiting for asynchronous function to finish, you can also show your loading message or spinner , you can catch and display errors, so basically this block fully handles async calls.
You can play with the code at Svelte’s REPL here.
Top comments (0)