Quick start with Svelte 3

Volha Alimava
5 min readFeb 2, 2021

Svelte is a new tool for creating modern web applications.

What is Svelte?

Let’s make clear with definition. According to official GitHub page Svelte is a new tool to build web applications.

It’s a compiler that takes your declarative components and converts them into efficient JavaScript that surgically updates the DOM.

But what does it mean exactly? Svelte behaves as so-called disappearing frameworks. It means that it converts your declarative code into imperative at build time instead of interpreting the code at run time. That means that bundle has optimized JavaScript, HTML, and CSS modules with instructions how to effectively update the DOM. In other words, makes magic and disappears like a faery.

So there is no need to use Virtual DOM or other high abstractions to find out which DOM elements should be updated. It is expected to increase performance and freeing up memory that usually is spent for Virtual DOM diffing work.

How to cook?

Let’s create a simple shopping cart to get accustomed with Svelte way. It’s a good example to learn syntax quickly, how parent-child event flow works, how to use reactivity and so on.

First things first let’s install Svelte template starter. To do this run these commands in your terminal:

npx degit sveltejs/template my-svelte-project
cd my-svelte-project
npm install
npm run dev

We have a simple design of our shopping cart with highlighted components that we’ll build. If you already know React, Angular or Vue you’ll find Svelte easy to go. It applies component-based approach we used to follow working with these frameworks. So let’s look at our design and divide it on components.

Components scheme

Cool! Now we can easily create a code structure based on this scheme:

  1. Shopping cart component
  2. Product list component
  3. Product item list component
  4. Product counter component

Our code structure looks like this:

- public
- images
circleCactus.svg
emptyCart.png
fatCactus.svg
redCactus.svg
- src
- components
- counter
Counter.svelte
- productList
ProductList.svelte
- productListItem
ProductListItem.svelte
- shoppingCart
ShoppingCart.svelte
App.svelte
mockData.js

Root Svelte component that has been created by template command imports our Shopping Cart. Svelte component has 3 possible modules: <script>, <style> and markup. Svelte syntax looks pretty similar to Vue and intuitively clear. In Vue markup is written inside a <template> tag. In Svelte there is no need to wrap in. Apart from that you’ve probably noticed that <style> is optional tag here as well as <script>.

This is our static data which can be easily replaced by a real database. You can expand and play with fetching data, write new features or whatever you want.

Where is state?

This is our main component, let’s say, smart container which obtains mock data, passes it to children and manages all manipulations with this data. Variables name and products are state of the component. Having this shopping cart we are able to change count of particular product or delete one or many positions from the basket.

But we need to force the component to reflect on our actions. How can we change the state? Easy! All what you need to do is to assign a new value (in our case a new array of products) in a state variable — products.

That’s it! Svelte updates DOM when component state changes. It knows how to do this quickly — it already has a plan that was built during the compilation. Remember how we pass an event on:changeCount to apply a new value. We’ll talk about it in detail below.

Where are props?

At first, Svelte syntax looks a bit weird, because it overrides some JavaScript things and gives a brand new meaning to them. As you can see above ProductList component exports products and onRemove variables. This syntax means that we expect some props passed somewhere in the application where this component is used. Also we apply default values (empty array and null) in case they are not passed in the component.

Next we have totalPrice with $ before it. This special symbol is valid in JavaScript, but in Svelte it’s needed to declare some reactive state that has dependency from other state variables and recalculate if they change. This behavior is something similar to the computed properties in Vue.

If there are no products in the cart it would be nice from UX perspective to display an empty cart icon and hide total price label. To do that we can use else statement inside each block where product list is printed and if statement in order to hide some piece of layout based on any condition.

Do I need a key?

In ProductList component you probably noticed on 44 line of code that there is (product.id) statement and it’s not clear. What is it and why do we need this? It’s not required and you can delete it without breaking anything. But when we are working with arrays in Svelte and we know that we will need to update one particular item instead of updating the whole list (or we need to make insertions at the beginning of the list) we need to provide some kind of unique key to identify each of them.

Without this key Svelte by default changes items from the end of the list and updates all of them. Having some identifier which could be an object, string or number and Svelte knows what it needs to make it happen.

In ProductListItem component we are expecting all properties of product as props because we used a destructuring product object in ProductList component. Other option here is to pass the whole object and then use spread operator. Both options are fine, choose what suits you more.

In <style> tag Svelte incapsulates styles in the scope of particular component. So we don’t need to worry about styles overriding. But if you want to share some styles for other components you just need to wrap by :global some selector to be shared.

Do you remember about on:changeCount event that we pass into components? This event is custom! Using createEventDispatcher function from Svelte API we can easily create our own event, give it a name in dispatch function as first argument and use around the application. Moreover we are free to pass as a second argument whatever we need to modify product count and price: in our example it is id and type of action: addition or subtraction.

Is that all?

No! Apart from what we already reviewed Svelte has great form bindings, lifecycle methods, stores and many other interesting things to build modern web applications. Svelte is gaining its ecosystem and community, and definitely looking his own place on the market.

--

--