Why you should try Svelte

by Marc Radziwill | January 15, 2020 | 5 minutes to read

Check out what you need to know for your first component in Svelte and learn the main advantages of version 3 from the compiler framework. Why you should try Svelte and how you can implement your first component

Web performance workshop

devcademy by Marc Radziwill

Web Performance is still one of the most underrated topics in web development. Even though it can help us, our companies and customers with their and our business, make our website more accessible for people with a slow network and has a significant impact on a sustainable internet.

become a web performance expert

Intro to Svelte

I recently came across the new rising star again when I watched the stateofjs 2019. They received the "Prediction Award" which means they are "awarded to an up-and-coming technology that might take over… or not?".

I read about Svelte last year but nothing caught me so that I forgot about it. But stateofjs 2019 made me curious so I visited their website.

My first impression was ok. It is:

a radical new approach to building user interfaces...

and Svelte

writes code that surgically updates the DOM when the state of your app changes.

Okay nice...yeah that sounds nice! I didn't know at this moment, that I will recommend the framework for your next app but it got my attention. I am into ReactJs and Angular for years and I thought that enough frontend frameworks to be known in deep. I took a look at VueJs and I liked it as well but I never used it in a project.

Back to topic! They encourage you to read their "introductory blog post" so I continued. And here it started. You all should watch the video from Rich Harris about "Rethinking Reactivity" from You Gotta Love Frontend Code Camp. Even if you are not interested in learning Svelte, if you only like ReactJs, Vue or any other reason. The talk is very entertaining. 🚀

Rich Harris - Rethinking reactivity

Tl;dr

Check out what you need to know for your first component in Svelte and learn the main advantages of version 3 from the compiler framework.


Table of Contents

  1. What is Svelte?
  2. Why you should try Svelte?
  3. Where can you try it?
  4. How to start with your first component?
  1. What's next?

1. What is Svelte?

So what is it? It is a component framework. You basically define components and reuse them all over your web app, website or whatever you are implementing. Just like in ReactJs VueJs or any other framework. But what is the difference? One of the main difference is, that runs at build time.

But what does that mean, it runs at build time? This means Svelte is more a compiler instead of a runtime component framework. It does not need any abstraction layer at in the browser to run your code. It compile the components you implements into plain JavaScript code.

Plain JavaScript or Vanilla JavScript is loved by all browsers because this highly efficient code can be parsed and executed faster than any other. Because it is plain JavaScript, your code changes the DOM directly. Svelte does not need a virtual DOM to simulate fast updates to the user.

Additionally, it comes with its build-in reactivity mechanism. Therefore you don't need any state management or external data binding library to sync your dynamic div class attribute.

Web performance workshop

devcademy by Marc Radziwill

Web Performance is still one of the most underrated topics in web development. Even though it can help us, our companies and customers with their and our business, make our website more accessible for people with a slow network and has a significant impact on a sustainable internet.

become a web performance expert

2. Why you should try Svelte

...Frameworks are primarily a tool for structuring your thoughts, not your code. (Rich Harris)

Svelte is a framework. React and Angular are one as well and we could also consider using VueJs. What are the main arguments for using Svelte?

  1. At deployment, you get vanilla JS, that running in your browser. Fast and plain JavaScript

  2. Apps developed are highly compatible. For example, if you develop a nice timer in Svelte you can use the compiled version of your widget in any other framework. Why? Take a look at No. 1 it is VanillaJS.

  3. Without the abstraction layer of a runtime framework, you serve less code to the browser. Code splitting can be much more valuable. You just serve your code without the framework code.

  4. The maintainers are free in their choice of the features they want to include in the framework. As Svelte itself is not in the compiled JavaScript output they can add features without worrying about performance issues for users in runtime. They can add a bunch of features and none of us developers has any disadvantages because of the bundle size.

  5. It is always good to keep an eye on such great approaches. And in terms of performance and user experience I think JAMStack applications like GatsbyJs are indispensable.

SPOILER: The team behind also develops Sapper - The next small thing in web development

3. Where can you try it?

The easiest way is to use their REPL. REPL is an online editor where you can check out the framework features in your browser. I recommend you to complete the tutorials as well. They are built on each other very well, but still independent if you just want to jump between features.

4. How to start with your first component?

If you want to build the app on your local machine make sure you install NodeJs. Otherwise, you can use the REPL.

In this case, we use Node to install and ie npx command to install the development environment on our local machine.

npx degit sveltejs/template svelte-tutorial

cd svelte-tutorial

These commands download all necessary files for us and we need to finish that setup with npm install to install all dependencies listed in our package.json.

Run npm run dev to start and visit localhost on port 5000 in your browser.

Now we are ready to implement our first component.

Terminal showing the start of the development server

Visit your browser on localhost:5000 and check if the page is running.

Running development server on localhost:5000

Before we start coding let's have a quick look on the component basics:

Component parts

A component is declared in a .svelte file and contains three main parts.

  1. Markup

You code your Html in every component file. I have my Html at the bottom of my file. For example, a very simple component without style and JavaScript looks like this.

SimpleHeadline.svelte

1<h1>Hello world!</h1>
  1. Styles

You component styles are wrapped between <style> tags and contain the Html for your component. We add some styles to our headline above and I rename the file.

StyledHeadline.svelte

1<style>
2 h1 {
3 font-size: 42px;
4 }
5</style>
6
7<h1>Hello world!</h1>
  1. JavaScript

We add <script> tags to our file. The script block contains the JavaScript logic. To illustrate that I create another file called DynamicStyledHeadline.svelte.

1<script>
2 let name = 'Nora';
3</script>
4
5<style>
6 h1 {
7 font-size: 42px;
8 }
9</style>
10
11<h1>Hello {name}!</h1>

See how I also added the same variable into curly braces in the html {VARIABLE}. This is how you make the variable accessible for the template.

1<script>
2 import SimpleHeadline from './components/SimpleHeadline.svelte';
3 import StyledHeadline from './components/StyledHeadline.svelte';
4 import DynamicStyledHeadline from './components/DynamicStyledHeadline.svelte';
5</script>
6
7<style>
8 main {
9 /* ... */
10 }
11</style>
12
13<main>
14 <SimpleHeadline />
15 <StyledHeadline />
16 <DynamicStyledHeadline />
17 <!-- ... -->
18</main>

If you import the component into your App like above, you can see the DynamicStyledHeadline on your local page.

image showing three different headlines to illustrate the function of svelte components

⚠️ Markup sanitization ⚠️ If you want to insert markup into you variable you can use an annotation like syntax. {@html string} will not sanitize your markup. You should escape it manually.

1<script>
2 let string = 'this string contains some <strong>HTML!!!</strong>';
3</script>
4<p>
5 {@html string}
6</p>

Svelte warnings

What I really like are the warnings the framework is providing. In the example below you a warning appears, that no alt attribute is found. You can see the warning on your local development environment or in the REPL.

1<script>
2 let src = 'tutorial/image.gif';
3</script>
4
5<img src="{src}" />
6<img {src} />
7<!-- shorthand -->
8
9<!-- svelete expects this line with the alt attribute: <img {src} alt="A man dances."> -->

Component logic and conditional rendering

If/else statements

In most cases of your application, you need to render the markup in dependency of your application or component state. In Svelte you implement this with if/else statements. If you used handlebars in any project they might look familiar to you. Any conditional block starts with an # and ends with a /. If you want an else block you use the : character like below. An else block can be plain or with another if-statement.

1<script>
2 let name = 'Nora';
3</script>
4
5{#if name === 'Nora'}
6<p>{name} - What a beautiful name.</p>
7{/if} {#if name === 'Nora'}
8<p>{name} - What a beautiful name.</p>
9{:else if name === 'Linda'}
10<p>{name} - I like that name</p>
11{:else}
12<p>{name} - The name is also beautiful.</p>
13{/if}

Loops in Svelte

I real world we need to loop over data. Like an if-statement, you start the block with # and end with / character. You can loop over any object as long as it has a length property. You can loop over generic iterables with each [...iterable]. In our case, we loop through the names array and access the current name with the help of the as keyword. Additionally, we get the current index as the second parameter.

You can use the destructuring syntax as well. In this case, you use each names as { name }.

1<script>
2 let names = [{ name: 'Nora' }, { name: 'Linda' }, { name: 'Helga' }];
3</script>
4
5<h1>Beautiful names</h1>
6
7<ul>
8 {#each names as currentName, index}
9 <li>
10 <a
11 target="_blank"
12 href="https://en.wikipedia.org/wiki/{currentName.name}_(name)"
13 >
14 {currentName.name}
15 </a>
16 </li>
17 {/each}
18</ul>

Waiting for data with the await block

As we all have to deal with asynchronous in web development, we also have to wait for it. The JavaScript language features like the await keyword helps us with that. In Svelte we get a handy syntax to wait for a promise to resolve: #await 🚀.

1<script>
2 let promise = getRandomNumber();
3
4 async function getRandomNumber() {
5 const res = await fetch(`tutorial/random-number`);
6 const text = await res.text();
7
8 if (res.ok) {
9 return text;
10 } else {
11 throw new Error(text);
12 }
13 }
14
15 function handleClick() {
16 promise = getRandomNumber();
17 }
18</script>
19
20<button on:click="{handleClick}">
21 generate random number
22</button>
23
24{#await promise}
25<p>...waiting</p>
26{:then number}
27<p>The number is {number}</p>
28{:catch error}
29<p style="color: red">{error.message}</p>
30{/await}

5. What's next?

You find all the resources for this article on GitHub. Feel free to check it out, try some stuff or fork it.

You should now be well packed for your first component. If you want to dive deeper, I recommend taking an hour or two of your time and going through the official Svelte training tutorial. 👨‍🏫

If you like this article, share it, follow me an subscribe to my newsletter.

Cheers Marc

Discuss on Twitter

stay up to date!

Sign up for my free newsletter and get your dose of technical education and inspiration.