An Introduction To Svelte

An Introduction To Svelte

Svelte has recently topped the satisfaction rankings of "State of JS 2020" and this justifies an introduction for everyone still not aware of it.

What is Svelte?

Svelte is a component-based frontend framework like React and Vue, that promises:

  • Less code
  • No virtual DOM
  • True reactivity

and delivers on all of these pretty well.

It currently has 41.2k stars on GitHub and an active community, including 359 contributors. The community is pretty active and unlike React, there is no huge corporation backing it. But no need to worry, Svelte won't vanish anytime soon. The project is licensed under the MIT license and was initially released on November 26, 2016, by Rich Harris, its creator. Svelte itself is implemented in TypeScript.

How does it work?

Unlike React or Vue, Svelte doesn't use a virtual DOM. Instead, it comes with a compiler that parses your code and emits code that precisely updates the DOM. This means that no diffing needs to take place, anymore. Only gradual DOM updates which a browser can handle pretty well. And this compiler can do even more. Svelte doesn't need hooks to update a component's state. A simple, plain JavaScript statement is enough. That statement is then compiled into something that actually handles state changes.

Like React has its .jsx files, and Vue has its .vue single-file components, Svelte has *.svelte files. And similar to single-file components in Vue, a svelte file can contain HTML, JavaScript, and CSS.

You can take a look at this sample component:

<script>
  const greeting = "Hello Svelte!";
</script>

<style>
p {
  margin: 0 auto;
}
</style>

<p>{greeting}</p>

To give you an example of Svelte's built-in reactivity, take a look at the component shown below. No (React) hooks, no redux, no state-management library, only plain JavaScript and a directive. This is the power of the Svelte compiler. What you see is relatively trivial code, but it's enough to make the outcome fully reactive. The same functionality in React would take you more code to write.

<script>
  let count = 0;

  function handleClick() {
    count += 1;
  }
</script>

<style>
  button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
  }
</style>

<button on:click={handleClick}>
  Clicked {count} {count === 1 ? "time" : "times"}
</button>

There are also more advanced features, like lifecycle-hooks and conditional rendering (which isn't plain JS anymore) which open up more use-cases. If you, for example, want to render a block for each entry in an array, below is how you do it with Svelte.

<script>
  const entries = [{
    id: "12345",
    entry: "Svelte"
  },
  {
    id: "23456",
    entry: "React"
  },
  {
    id: "34567",
    entry: "Vue"
  }
];
</script>

<ul>
  { #each entries as { id, entry }, i }
    <li>{id}: {entry}</li>
  { /each }
</ul>

That's not plain JavaScript, anymore, but it's still a readable syntax that is necessary for the compiler to be able to process it.

What makes Svelte so powerful?

Simplicity and the power that comes with Svelte's approach make it so powerful. Virtual-DOM implementations made single-page applications remarkable, but they come at a cost. Diffing the virtual DOM and the actual DOM, and then applying gradual changes at runtime costs performance and sometimes brings complexity. Moving all this into a compile-step and then letting the browsers do what they are good at (managing the DOM) makes your apps faster, and your bundle-sizes lower. What you deliver is your frontend code, and a lot less library/framework weight.

Oh, and do you still remember the reactive example? Here is how the emitted JavaScript code looks. That's a lot of burdens taken off your back and put onto the compiler's shoulder.

/* App.svelte generated by Svelte v3.32.1 */
import {
    SvelteComponent,
    append,
    attr,
    detach,
    element,
    init,
    insert,
    listen,
    noop,
    safe_not_equal,
    set_data,
    space,
    text
} from "svelte/internal";

function create_fragment(ctx) {
    let button;
    let t0;
    let t1;
    let t2;
    let t3_value = (/*count*/ ctx[0] === 1 ? "time" : "times") + "";
    let t3;
    let mounted;
    let dispose;

    return {
        c() {
            button = element("button");
            t0 = text("Clicked ");
            t1 = text(/*count*/ ctx[0]);
            t2 = space();
            t3 = text(t3_value);
            attr(button, "class", "svelte-pl9c4u");
        },
        m(target, anchor) {
            insert(target, button, anchor);
            append(button, t0);
            append(button, t1);
            append(button, t2);
            append(button, t3);

            if (!mounted) {
                dispose = listen(button, "click", /*handleClick*/ ctx[1]);
                mounted = true;
            }
        },
        p(ctx, [dirty]) {
            if (dirty & /*count*/ 1) set_data(t1, /*count*/ ctx[0]);
            if (dirty & /*count*/ 1 && t3_value !== (t3_value = (/*count*/ ctx[0] === 1 ? "time" : "times") + "")) set_data(t3, t3_value);
        },
        i: noop,
        o: noop,
        d(detaching) {
            if (detaching) detach(button);
            mounted = false;
            dispose();
        }
    };
}

function instance($$self, $$props, $$invalidate) {
    let count = 0;

    function handleClick() {
        $$invalidate(0, count += 1);
    }

    return [count, handleClick];
}

class App extends SvelteComponent {
    constructor(options) {
        super();
        init(this, options, instance, create_fragment, safe_not_equal, {});
    }
}

export default App;

Can you recall all those integration libraries that make many other libraries compatible with the virtual DOM? Yes, I know that you don't always need those. But with Svelte, you'll never need them, because there simply is no virtual DOM.

Is it worth a try?

In my opinion, it's definitely worth a try. It is a fresh approach to a common problem, which tries to put a lot of effort into making things simpler for developers. The official documentation is awesome, with a great tutorial going over every important feature. It's written very well and makes it easy to follow along.

So, if you happen to have some spare time, maybe try it out, it may well be worth your time.

Before You Leave

If you liked this article, feel free to visit me on Twitter. I regularly post content there. It is basically the platform where you will find my content first before it lands on my blog or somewhere else.