Recently, I’ve played a little bit with Svelte, and I wanted to share some thoughts.
Svelte claims to be a new approach, and this is what I like. But how? What makes it so unique?
There won’t be a lot of code.
Check their documentation. It’s pretty useful. Here, I want to focus on how I understand Svelte and why I find it crazy good.
In short, no virtual DOM
Svelte’s creator compares his creation to React and other frameworks to explain his approach.
Instead of creating a virtual DOM and applying a diffing algorithm, Svelte converts your code into a “super-efficient VanillaJS code” that updates DOM only when necessary.
The HTML tags used in your
.svelte files, e.g.
h1, are added the same way as in vanilla, but with Svelte, it’s full declarative and thus pretty much faster to write.
Besides, it’s really like classic web development with HTML/JS/CSS so that you won’t be intimidated, and you won’t have to learn thousands of additional concepts.
It’s a compiler
The big difference with Svelte is that it calculates things in advance, at build time.
- First, it parses
.sveltefiles with its internal parser to build an abstract tree (AST)
- Then it reads this AST to collect variables and dependencies (~ nodes)
- Then it creates code blocks (Fragment) for each node
There is no runtime overhead, in fact, no runtime at all. It only embeds what is essential. Because of that, the browser has less work and less code to evaluate.
Svelte generates small bundles of CSS and JS you can add to your HTML page.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>My website</title> <link rel="stylesheet" href="/build/bundle.css" /> <script defer src="/build/bundle.js"></script> </head> <body></body> </html>
Rich Harris introduced Svelte 3 with a catchy slogan: “Rethinking reactivity”.
But what is reactivity?
The reactivity is quite essential, not just for developers. It shows how the pages respond to user interactions.
As with many other tools, you can split your app into several components with Svelte. Each component can have its styles and scripts without affecting the children (nested components).
Svelte is a superset of HTML so that you can use the
<style> and the
<script> tags. See it in repl.
Let’s take a step back
What I like the most with Svelte is that it’s a compiler. It’s crazy efficient, and you do write less code.
However, I think not all benchmarks make sense, as nobody runs thousands of updates per second, so saying that Svelte is 50 times faster than React is probably valid but not meaningful from a user perspective.
Nevertheless, Rich Harris is quite honest about that:
we are abusing the language for fun and profits
I hope you will give Svelte a try. It’s worth it.
It might be inappropriate, but I like Svelte for the same reasons I like Jekyll. It’s classic web development with HTML/JS/CSS with just a few additional concepts.