Yet Another JavaScript Framework has caught my attention. This time, it’s Svelte. I don’t build web pages often, but it’s good to know how to use a framework to be able to build the simple stuff I do. I’ve experimented a bit with the mainstream ones (Vue and React) but they are a little much. I need something simple and it looks like Svelte fits the bill.
I heard of Svelte in a newsletter from The Economist where they described how they produce some of their interactive web presentations and mentioned the Svelte framework (among a few other things). Since I’m a huge Economist fanboy, I thought I’d give Svelte a try.
So far, it looks interesting. I’ve gone through a brief tutorial and I like that it pretty much looks like basic JavaScript, HTML and CSS. Those things I know.
Getting it going was pretty easy. I decided to go with the old school way of doing things to learn the basics first and maybe I’ll try SvelteKit later.
Basically, I cloned https://github.com/sveltejs/template/ into a folder and ran npm install in the folder. Then edited the App.svelte file to create a very simple book list:
<script>
import { fade } from 'svelte/transition';
let books = ['Learning Svelte', 'Zen of Cooking'];
let newBook = '';
function addBook(evt) {
if (evt.key === 'Enter') {
books = [...books, newBook];
newBook = '';
}
}
</script>
<label>
<h4>Add book</h4>
<input type="text" bind:value={newBook} on:keydown={addBook}>
</label>
<h4>My Books</h4>
<ul>
{#each books as book}
<li transition:fade>{book}</li>
{/each}
</ul>
<style>
input {
padding: 5px 10px;
}
li {
list-style: none;
}
ul {
padding: 5px;
}
</style>
Then npm run dev to compile and run the app. Pretty easy.
It’s very interesting that the .svelte files get compiled into an output that contains the relevant JavaScript, HTML and CSS. That allows for a simplification in the code that needs to be written since the compiler handles figuring out what will need to be updated dynamically in the DOM.
Although I just got started with this, I’ll learn a bit more and hopefully be able to build my Ovi goal tracker using Svelte pretty quickly.