Why you should try Svelte!
Tags: javascript, beginners, webdev, svelte
Published: 2020-04-28 06:50:35

## Intro to Svelte

I recently came across Svelte again when I watched the [**stateofjs 2019**](https://2019.stateofjs.com/awards/). 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 the [**website**](https://svelte.dev/).

---

If you like this article, smile for a moment, share it, follow me, check out my RSS feed and [subscribe to my newsletter](https://marcradziwill.com/newsletter/).

---

My first impression was okay.
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 Svelte for your next app, but they 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 Svelte! They encourage you to read their [**"introductory blog post"**](https://svelte.dev/blog/svelte-3-rethinking-reactivity), 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**](https://www.israel.yglfconf.com/). Even if you are not interested in learning Svelte, if you only like ReactJs, Vue or any other reason. The talk is very entertaining. 🚀

{% youtube AdNJ3fydeao %}

## 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.

I posted this article initially on my [blog](https://marcradziwill.com/blog/why-you-should-try-svelte/).

<hr />

## Table of Contents

1. [What is Svelte?](#whyuse)
2. [Why you should try Svelte?](#whytry)
3. [Where can you try it?](#where)
4. [How to start with your first component?](#firstcomponent)
   - [Component parts](#parts)
     1. [Markup](#makup)
     2. [Styles](#styles)
     3. [JavaScript](#javscript)

- [Svelte warnings](#warnings)
- [Component logic and conditional rendering](#rendering)
  1. [If/else statements](#ifelse)
  2. [Loops in Svelte](#loops)
  3. [Waiting for data](#waiting)

5. [What's next?](#next)

## 1. What is Svelte? <div id="whyuse"></div>

So what is it? Svelte is a component framework. You 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. Svelte compile the components you implement into plain JavaScript code.

All browsers love plain JavaScript or Vanilla JavaScript 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.

## 2. Why you should try Svelte <div id="whytry"></div>

> ...Frameworks are primarily a tool for structuring your thoughts, not your code. ([Rich Harris](https://svelte.dev/blog/frameworks-without-the-framework))

Svelte is a framework. React is 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 in Svelte are highly compatible. For example, if you develop a 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 Svelte 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: Svelte also develops [Sapper - The next small thing in web development](https://sapper.svelte.dev/)

!['Mind-blowing gif' Mind-blowing gif](https://marcradziwill.com/8ea40ab6c639c0257ed3d7ee0f1d47e6/mind-blow.gif)

## 3. Where can you try it? <div id="where"></div>

The easiest way is to use their [REPL](https://svelte.dev/repl/). REPL is an online editor where you can check out the framework features in your browser. I recommend you to complete the [tutorials](https://svelte.dev/tutorial/basics) as well. They are built on each other very well, but still independent if you just want to jump between features.

[![Web Performance Checklist](https://dev-to-uploads.s3.amazonaws.com/i/i9nrcwt53letp80a28eg.png)](https://devcademy.marcradziwill.com/web-performance-checklist/)

## 4. How to start with your first component? <div id="firstcomponent"></div>

If you want to build the app on your local machine, make sure you [install NodeJs](https://nodejs.org/en/download/). Otherwise, you can use the REPL.

In this case, we use Node to install and the `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](https://marcradziwill.com/static/08b7ebc7c9bb8944d0b15709b714ce77/21b4d/svelte-localhost.png 'start of development server')

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

![Running development server on localhost:5000](https://marcradziwill.com/static/5731447953ddce1d669132b79cab1537/5c263/localhost.png 'running development server')

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

### Component parts <div id="parts"></div>

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

1. **Markup** <div id="markup"></div>

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

`SimpleHeadline.svelte`

```html
<h1>Hello world!</h1>
```

2. **Styles** <div id="styles"></div>

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`

```html
<style>
  h1 {
    font-size: 42px;
  }
</style>

<h1>Hello world!</h1>
```

3. **JavaScript** <div id="javscript"></div>

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

```html
<script>
  let name = 'Nora';
</script>

<style>
  h1 {
    font-size: 42px;
  }
</style>

<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.

```html
<script>
  import SimpleHeadline from './components/SimpleHeadline.svelte';
  import StyledHeadline from './components/StyledHeadline.svelte';
  import DynamicStyledHeadline from './components/DynamicStyledHeadline.svelte';
</script>

<style>
  main {
    /* ... */
  }
</style>

<main>
  <SimpleHeadline />
  <StyledHeadline />
  <DynamicStyledHeadline />
  <!-- ... -->
</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](https://marcradziwill.com/static/c5b1a44e48ac91a6e756f86bfadaa1f2/cd78c/headline.png 'headline component')

**_⚠️ 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.

```html
<script>
  let string = 'this string contains some <strong>HTML!!!</strong>';
</script>
<p>
  {@html string}
</p>
```

### Svelte warnings <div id="warnings"></div>

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

```html
<script>
  let src = 'tutorial/image.gif';
</script>

<img src="{src}" />
<img {src} />
<!-- shorthand -->

<!-- svelete expects this line with the alt attribute: <img {src} alt="A man dances."> -->
```

### Component logic and conditional rendering <div id="rendering"></div>

#### If/else statements <div id="ifelse"></div>

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.

```html
<script>
  let name = 'Nora';
</script>

{#if name === 'Nora'}
<p>{name} - What a beautiful name.</p>
{/if} {#if name === 'Nora'}
<p>{name} - What a beautiful name.</p>
{:else if name === 'Linda'}
<p>{name} - I like that name</p>
{:else}
<p>{name} - The name is also beautiful.</p>
{/if}
```

#### Loops in svelte <div id="loops"></div>

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 }`.

```html
<script>
  let names = [{ name: 'Nora' }, { name: 'Linda' }, { name: 'Helga' }];
</script>

<h1>Beautiful names</h1>

<ul>
  {#each names as currentName, index}
  <li>
    <a
      target="_blank"
      href="https://en.wikipedia.org/wiki/{currentName.name}_(name)"
    >
      {currentName.name}
    </a>
  </li>
  {/each}
</ul>
```

### Waiting for data <div id="waiting"></div>

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 help us with that. In Svelte we get a handy syntax to wait for a promise to resolve: `#await` 🚀.

```html
<script>
  let promise = getRandomNumber();

  async function getRandomNumber() {
    const res = await fetch(`tutorial/random-number`);
    const text = await res.text();

    if (res.ok) {
      return text;
    } else {
      throw new Error(text);
    }
  }

  function handleClick() {
    promise = getRandomNumber();
  }
</script>

<button on:click="{handleClick}">
  generate random number
</button>

{#await promise}
<p>...waiting</p>
{:then number}
<p>The number is {number}</p>
{:catch error}
<p style="color: red">{error.message}</p>
{/await}
```

## 5. What's next? <div id="next"></div>

You find all the resources for this article on [GitHub](https://github.com/marcradziwill/svelte-component-tutorial). 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 tutorial. 👨‍🏫

If you like this article, smile for a moment, share it, follow me, check out [my RSS feed](https://marcradziwill.com) and [subscribe to my newsletter](https://marcradziwill.com/newsletter/).

Cheers Marc