Svelte – the new kid on the block

by | 03.11.2022

Svelte. Or as the developers themselves call it: “Cybernetically enhanced web apps”.

You probably know the big players on the market: Angular, its big brother React and its little sister VueJS. All three are very well-established Javascript UI frameworks and have become indispensable in the web world. But now something new is entering the market: Svelte.

This immediately raises the question: Do you need it? Another new framework? In the following, I will get to the bottom of these questions.

The genesis of Svelte

The developers of Svelte asked themselves whether it would not be possible to remove all the ballast from the current UI libraries and still produce efficient and stable code?

With version 1 of Svelte, they tried to answer this question or rather confirm their hypothesis. They took the React framework and adapted it for their needs. The statement, “Svelte – the new kid on the block” is only half true, because version 1 of Svelte already saw the light of day in 2016. Interestingly, Angular, as we know it today, came onto the market at the same point.

With version 2, the developers of Svelte deepened their project and when they realised that their approach was pretty cool and could also help other developers, they did a complete roundup with version 3 in 2019 and gave the whole thing a clean makeover. Developer friendly and written entirely in Typescript. The Svelte UI framework was born.

Some differences between Svelte and other frameworks

UI frameworks are usually used to create web applications. And Svelte is also a UI framework, but without the whole “framework”. This sounds questionable at first, but on closer inspection it is really clever. Svelte is first and foremost a compiler. It converts what we type into specially written .svelte files into pure vanilla Javascript. And this opens up a whole new range of programming possibilities….

The word “svelte” describes very well its features compared to the big boys. By compiling it into simple Javascript code, tailored to the needs of the application, and removing any additional ballast, the size of a runnable application is reduced enormously. If an Angular application still manages with ~180 kB and ReactJS is already pushed down to about 6.3 kB, Svelte just laughs and reduces itself to a whole 3.5 kB. You really have to look with a magnifying glass to believe that.

And how does Svelte manage that?

  • For one thing, Svelte does not need a runtime library. By compiling it, all the necessary functions are brought into the finished application. A runtime library that provides all possible functionalities of the framework is therefore not needed here.
  • On the other hand, Svelte already provides many things that normally have to be extended with third-party libraries, such as reactiveness or so-called global state management. A look at the dependencies of a freshly set up Svelte application shows the same thing as a fridge in a student flat – yawning emptiness.

Angular or React use a so-called Virtual DOM1

for the current rendering of the interface. In simple terms, this is an image of the current DOM, which is then used to determine which elements in the interface have changed and need to be re-rendered by comparing them (diffing). Sounds very cost-intensive at first glance, but it is faster than a normal update cycle.

Svelte takes a different approach here2: Already during the compilation process, it replaces components with highly effective, imperative code that adapts the real DOM “surgically precisely” and thus works much faster than the other frameworks do.

A syntax for purists

The developers of Svelte asked themselves what a comfortable and yet performant API could look like. The answer was simple: the best API is no API. By pre-compiling, a .svelte file can be put into any form the Svelte developers wanted. Any ballast code can thus be avoided and bindings to classic Javascript conventions can be dropped.

A classic ReactJS component looks like this:

```
import React, { useState } from 'react';

export default () => {
               const [a, setA] = useState(1);
               const [b, setB] = useState(2);

               function handleChangeA(event) {
                              setA(+event.target.value);
               }

               function handleChangeB(event) {
                              setB(+event.target.value);
               }

               return (
                              <div>
                                            <input type="number" value={a} onChange={handleChangeA}/>
                                            <input type="number" value={b} onChange={handleChangeB}/>

                                            <p>{a} + {b} = {a + b}</p>
                              </div>
               );
};
```

Svelte appears much tidier in comparison:

```
<script>
               let a = 1;
               let b = 2;
</script>

<input type="number" bind:value={a}>
<input type="number" bind:value={b}>

<p>{a} + {b} = {a + b}</p>
```

In comparison, you can see that the ReactJS variant is almost 3x bigger! All the magic for binding and “reactiveness” happens at compile time without a developer having to worry about it. A simple variable assignment is converted something like this:

`count += 1;` becomes `count += 1; $$invalidate(‘count’, count);`

Out of the box global state management

When developing applications, the popular Redux Pattern is often used.3 Originally a Javascript library with roots in Facebook’s Flux Patterns4,

it is adapted and extended by other libraries. The goal is so-called global state management. Here, a global state is saved for the entire application (or just parts of it) and the state is changed by means of special triggers and functions (called actions and reducers).

Due to its high popularity, Svelte was designed to make work as easy as possible for developers. Thus, Svelte offers global state management by default and can be used in a simple way. Further external dependencies are thus kept at bay and the application remains lean. A win-win situation.

Whereas in other libraries the actions, reducers and selectors have to be laboriously written and moved to the right place in the project, this can be easily implemented in Svelte:

```
import { writable } from 'svelte/store';

<script>
               // defining the store
               export const myName = writable("Marco");
</script>

// Binding within a template
<span> My Name is {$myName}</span>

// Change state
<script>
               onMount(async () => {
                              $myName = "Polo";    
               });
</script>
```

The trick here is hidden in the $ sign. As soon as you write this symbol in front of the variable name, Svelte recognises that you want to work with the global state and adapts the output code accordingly at compile time. And of course the whole thing is reactive immediately.

Rendering – before, after and in the middle

Of course, one of the most important features must not go unmentioned by Svelte: Where programming languages and frameworks such as PHP or ASP.NET only offer server-side rendering (SSR), whereas Angular, VueJS and React are exclusively single-page applications (SPA), Svelte brings both worlds together5 and thereby creates completely new possibilities for application design.

Through special formatting of the file structure and the use of specially provided methods from the framework, data can already be aggregated during the retrieval from the server and integrated into the subsequently rendered page. The advantage is obvious: no further requests are needed via the internet to the server in order to initially load data. For example, a table with a large amount of data could be pre-filled at load time and then execute further requests (such as paging or sorting) in the browser as an SPA if they are needed.

ViteJS as kickstarter

Normally, an application consists of many different files. In addition, there are third-party libraries and the splitting into different modules, routes, configurations…

The “classic” web development has always used stable frameworks such as Webpack or RollupJS to carry out the so-called “bundling”. An application is bundled accordingly and then delivered to the browser. Depending on the configuration, this process is booted at development time with a development server or made ready for production for later deployment.

As the size of an application grows, so does its complexity. Many different routes and sub-modules are created and bundling takes longer and eats up additional resources. Despite Hot Module Replacement (HMR)6 the duration of the “hot loading” increases after a change has been made to the code, the save button has been pressed and the result has been viewed in the browser.

Svelte uses a newcomer here: with ViteJS7 the whole bundling is bypassed and the speed is reduced to a fraction. For comparison: a freshly set up Angular application needs about 15 seconds to start the development server, whereas Svelte needs only 2.7 seconds with ViteJS. Impressive, isn’t it?

ViteJS achieves this performance by behaving like a normal web server. Through native ESM8, it leaves the job of bundler to the browser and only delivers those modules and code parts that are really needed. This reduces the overhead and increases the speed.

When should you keep your hands off Svelte?

If you’re thinking “shut up and take my money”, it’s worth taking a look at the other side first. As nice as all this sounds, there are also good reasons not to opt for Svelte:

Svelte is not (yet) suitable for enterprise applications

As with any new framework on the market, it needs time to mature. In some places there are still major bugs, features are not yet implemented or breaking changes occur more frequently. Therefore, Svelte should not be considered for large enterprise applications (for now), especially since frequent refactoring quickly leads to frustration.

For small and medium-sized applications, however, Svelte is certainly already very useful.

Community support is low

Ask a question about Angular on Stack Overflow and you’ll probably get a 3-page answer in 5 minutes with 5 code examples and 10 references to read on. Still only growing in popularity, this driving force of community is simply missing from Svelte. This means that you have to do a lot of trial and error or read in the actual documentation or framework code. If you are afraid of this extra effort or if you lack the financial means for it, you should rather resort to one of the full-grown frameworks.

No time / no money for do-it-yourself work

Due to the focus on the core functionalities (and the lack of a big backer, as is the case with React or Angular), Svelte simply lacks important features such as dependency injection, which are available in other frameworks. So you may have to implement and maintain some features yourself.

Another framework is already in use

If you have already built up a team of developers who are intensively familiar with a framework, you should consider very carefully whether the introduction of a new, young framework is worthwhile for you. Since Svelte does nothing different from other frameworks at its core (namely rendering the user interface), the added value is too low to completely rebuild an existing application.

Seeing Svelte as an opportunity

With a different perspective, the disadvantages or “problems” mentioned can also turn out to be opportunities!

By using svelte parallel to the actual development, you can sustainably promote the know-how in the team.
In addition, the fresh approaches break up entrenched development patterns and encourage all participants to rethink.
The “compulsion” to do it yourself results in a much deeper understanding of the technologies already in use (anyone who has been passionate about Dependency Injection will only really understand how it works once they have written an Injector themselves).

Another plus point is the development of Web Components with Svelte. The simple syntax and lean output make it easy to create Web Components that you can then integrate into an existing system. On the one hand, this creates a certain framework independence, on the other hand, you can also outsource the development.

If you shy away from the lack of community support, here is a personal tip: Developers like you and me are “the community”. Become the support for others yourself! Knowledge and examples have to build up over time. However, if you are fresh to the topic and help others understand the framework and develop new applications, you will gain a good reputation among developers, and strengthen awareness of the framework step by step. Following the quote of Mahatma Gandhi: “Be the change you wish to see in the world”.

Conclusion

In summary, it can be said that Svelte brings a breath of fresh air into the world of web development with Javascript. The new approaches and technologies make it possible to implement new architectural patterns. The performance gain also brings multiple added value, both during development and later in the productive system.

Only the future can show how Svelte will hold its own on the market. From my perspective, the chances for “the new kid on the block” are good, especially since in my opinion it does not compete with the existing frameworks, but can exist wonderfully in parallel and expand the portfolio. For me, it is a very exciting and successful framework and I will implement one or the other project with it. Likewise, I have already heard from other developers that it is being used to gradually migrate old-established PHP applications into a single-page application – doesn’t sound bad, does it?

 

Notes:

[1] Virtual DOM
[2] Svelte: Rethinking Reactivity
[3] Redux Pattern
[4] Flux Pattern
[5] What is SvelteKit?
[6] Hot Module Replacement
[7] ViteJS
[8] Native ESM

If you like the post or want to discuss it, feel free to share it with your network.

Marco Rehmer
Marco Rehmer

Marco Rehmer is a front-end developer and worked at t2informatik from the beginning of 2021 to the end of 2023. Since then he has been working as a freelancer, also for t2informatik. In addition to UI/UX design principles and architectural patterns, he also has a healthy passion for coffee from all over the world. And when he’s not sitting in front of the keyboard, he hangs out on the occasional climbing wall and looks at the world from above.