Svelte

Same but different: Introduction to Svelte

No Comments

Compared to the past few years, the JavaScript world has become relatively quiet lately. Especially in the frontend React, Angular, and with some distance Vue are established and delight a growing user base. Component-based approaches have gained acceptance here and WebComponents are still a possible next development step, which could rather be the foundation for the established frameworks as a real alternative.

Svelte is not reinventing the wheel, but is gaining more and more attention in the community. In this article, I would like to highlight what Svelte has in common with the established approaches and where it comes to breaking new ground.

About Svelte

Svelte is a component-based framework just as we already know it from React, Angular and Vue, but differs from the established top performers in one important aspect: they require declarative, State-driven code, which the browser has to convert into DOM operations using techniques like a Virtual DOM.

Svelte is not a classical framework but rather a compiler, which converts the code into highly efficient imperative code and manipulates the DOM directly. Since Svelte does not require any framework code, it produces smaller bundles, and without a Virtual DOM in memory it promises better performance.

This sounds quite promising and already feels very good in practice. Unfortunately, the IDE support is not comparable to the established frameworks but the official site helps a lot.

A glance at Svelte

Once your IDE is set up, you can use one of the predefined templates to set up a Svelte project. On svelte.dev the use of degit is recommended, and simple project templates for rollup and webpack are available.

Using webpack, the whole thing looks like this:

npx degit sveltejs/template-webpack svelte-app
cd svelete-app
npm install
npm run dev

Hello world example

Now that we have a project up and running, we can take a brief look at the components: these are stored in .svelte files and at first glance look quite similar to the components we know from Vue. Inside a <script> element JavaScript code can be written and inside a <style> element the corresponding CSS code can be found.

We open the file App.svelte in the folder src and change the content as follows:

<script>
  const name = "world!"
</script>
 
 
<style>
  h1{
    color:blue;
  }
</style>
 
<h1>Hello {name}</h1>

Svelte now converts this code into JavaScript code in the build process. In the Svelte REPL you can have a look at it and play around with Svelte.

To make our application a bit more exciting we create a new Headline component which we can control via properties:

<script>
  export let text = "A sample headline";
</script>
 
 
<style>
  h1 {
    color: purple;
  }
</style>
 
<h1>{text}</h1>

Properties are exported inside the script element and can also be assigned a default value.
In our App.svelte we now import the headline and add it to the code:

<script>
  import Headline from "./Headline.svelte";
  const name = "world!"
</script>
 
 
<style>
  h1{
    color:blue;
  }
</style>
 
<h1>Hello {name}</h1>

Looking at the application in the browser, we notice that both headings have different colors.

Svelte Appliation in the browser

This is because each Svelte component has its own styling (scoped styles), which makes it very easy to create components with CSS.

Control structures

Control structures can be realized in Svelte via the templates. For example, an if condition looks like this:

<script>
  export let level = 2;
  export let text = "Some headline"
</script>
 
{#if level===1}
<h1>{text}</h1>
{:else}
<h2>{text}</h2>
{/if}

The option to define a fallback if no elements can be output is particularly useful for loops:

<script>
  export let items = ["Hello", "World"];
</script>
 
{#each items as item}
{item}
 
{:else}
 
no item provided
 
{/each}

Last but not least: Svelte also allows us to handle asynchronous requests and represents the load state, the result, and the error case using the template syntax:

<script>
  async function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
</script>
 
{#await timeout(2000)}
sleeping
 
{:then}
 
awake!
 
{:catch}
 
error :(
 
{/await}

Although the template syntax is a bit unusual in the beginning, it has some very useful features that improve the readability of your code.

And much more

Svelte also has a few other useful features to convince you. It is pretty easy to implement 2-way binding, and also friends of animation will find some possibilities to create a presentable result in no time using Svelte. The integration of slots is also pretty nice, as you already know it from Vue. There are several possibilities to create very flexible components. Even sophisticated state management is possible with an own store-implementation. But this is certainly worth a seperate post on the blog.

If you want to take a closer look at all the possibilities Svelte offers, you should try the official tutorial.

Besides Svelte it is also worthwhile to have a look at Sapper (App Framework comparable to next.js) and Svelte Native (comparable to React Native).

TypeScript users still have to wait out for Svelte. However, the integration is in progress and has a high priority.

Conclusion

Svelte is an inspiring approach that allows you to build applications without using much boilerplate. Unfortunately, the IDE support is not yet comparable to the other solutions on the market, and also the available components have to be cut back. A good entry point is the official Svelte community website. Svelte looks very promising and is getting more and more attention lately.

Picture: Ferenc Almasi

Daniel Mies

Daniel is part of the codecentric team as a IT-Consultant since 2015. He likes to work in backend as well as in the frontend.

Currently his focus lies on IoT and Industry4.0 where he supports companies as product owner in their projects.

Comment

Your email address will not be published. Required fields are marked *