Intro to Svelte
I recently came across Svelte 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 the website.
If you like this article, smile for a moment, share it, follow me, check out my RSS feed and subscribe to my 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", 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. ๐
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.
Table of Contents
- What is Svelte?
- Why you should try Svelte?
- Where can you try it?
- How to start with your first component?
1. What is Svelte?
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
...Frameworks are primarily a tool for structuring your thoughts, not your code. (Rich Harris)
Svelte is a framework. React is one as well, and we could also consider using VueJs. What are the main arguments for using Svelte?
At deployment, you get vanilla JS, that running in your browser. Fast and plain JavaScript
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.
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.
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.
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
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 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.
Visit your browser on localhost:5000 and check if the page is running.
Before we start coding, let's have a quick look at the component basics:
Component parts
A Svelte component is declared in a .svelte
file and contains three main parts.
- Markup
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
<h1>Hello world!</h1>
- 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
<style>
h1 {
font-size: 42px;
}
</style>
<h1>Hello world!</h1>
- 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
.
<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.
<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.
โ ๏ธ 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.
<script>
let string = 'this string contains some <strong>HTML!!!</strong>';
</script>
<p>
{@html string}
</p>
Svelte warnings
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.
<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
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.
<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
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 }
.
<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
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
๐.
<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?
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 tutorial. ๐จโ๐ซ
If you like this article, smile for a moment, share it, follow me, check out my RSS feed and subscribe to my newsletter.
Cheers Marc
Top comments (11)
Nice article. I really wanted to know a bit more about Svelte since it is coming up on my radar more and more. I am new to the frontend world and currently learning React. It would be nice to know why one would choose Svelte over React. It seems that they both solving the same problems.
Are there any particular strengths of this framework over React?
Thank you gyurisc :)
So welcome to the frontend world :D you will love it ;)
You really should try Svelte if you have some spare time.
As I'm doing much web performance stuff, I like the fact to ship my application without the framework code to production. Svelte shifts the work into the compiler. For React, in particular, you need the framework code in your production app. Reacts production code is not an overhead, because they help you with a lot of things you would have to implement yourself, but it is still code that has to run.
I would love to have an overview or blog post about a comparison on just the technical facts. But your right, they try to solve similar problems. You can add VueJs and some others.
Moreover, Rich Harris deceived us all by making us think of Svelte as a UI framework ;). Maybe with Svelte you learning a new language instead of a frontend framework :)
Thanks for the great answer and the article! I will read it :)
Marc, this is a well written article with plenty of details.
gyurisc, I wrote a similar post from a perspective of why I went from React to Svelte if you're curious: mikenikles.com/blog/why-i-moved-fr...
Hey Mike, thanks so much.
I read your article as well. Nice comparison!
Really great article! I am starting to like this... Will make an example in Svelte to try it out. Thanks!
I was just about to ask where the link is but then I realized that I can google it myself too :)
Scrimba Svelte training
It's very much like the excellent RiotJS that predates it by a number of years
Hey Jo, thanks for that hint. I've to admit that RiotJS and I haven't met in detail. I will put it on my coding bucket list!
Nice article! You can quick start with svelte by using hqjs.org