DEV Community

Cover image for ⏰ Svelte Crash Course (in 10 pics!)
Xiaoru Li for The Method Coder

Posted on • Updated on • Originally published at twitter.com

⏰ Svelte Crash Course (in 10 pics!)

Originally posted on Twitter as a thread: https://twitter.com/hexrcs/status/1185186492982943744


Huge Update: Video Version Now Available!

👉 YouTube Playlist - Only 13 minutes in total! 🥳


Always wanted to check out Svelte (aka. "the next big thing in web dev") but never got time for it? ⏰

🔥 I've got a 10-minute crash course for you! 👇

(Spoiler alert: Svelte is so intuitive and easy to use that you may feel like you already know it! 🥳)

1 - How Svelte works

  • Compiler: Doesn't ship a Svelte "library" to users, but build-time optimized plain JS
  • Components: App is made up of composable UI elements
  • Reactive: Event/User interaction triggers chain of state changes, auto-updating components throughout the entire app

How Svelte works

2 - UI Is a Component Tree

A component defines how your app should interpret some abstract "state" values, so that it can turn them into DOM elements in your browser, and ultimately pixels on your screen.

UI Is a Component Tree

3 - The Anatomy of a Svelte Component

Each .svelte file contains a single component, consisting of 3 parts:

  • <script> is component logic in JS
  • <style> is CSS styling, scoped and applied to only the current component
  • Svelte template, based on HTML but can use custom components and inline logic (like JSX)

The Anatomy of a Svelte Component

4 - The Svelte Template

The Svelte template allows us to use our own custom components in addition to HTML elements. The .svelte file extension is optional if there's no ambiguity, but the first letter of a custom component MUST be in uppercase.

We can use JS expressions inside curly braces { }.

The Svelte Template

5 - Setting "Props"

A common way to "control" how a child component behaves is to pass data into it as props (properties).

To accept a prop, expose a variable with export. It's important to use let because const is not reassignable.

Setting a prop is just like doing regular HTML.

Setting "Props"

6 - Updating Component States

User actions trigger events. on: lets us listen to events and fire functions to update states. State changes will auto-update the UI.

Data generally flows from a parent to a child, but we can use bind: to simplify the state-update logic by allowing two-way data flow.

Updating Component States

7 - $: Reactive Statements

"Reactive statements" are those statements marked by $:.

Svelte analyzes which variables they depend on. When any of those dependencies changes, the corresponding reactive statements will be rerun. Very useful for declaring derived states, or triggering "side effects".

Reactive Statements

8 - Reactive State "Store"

A reactive "store" makes it easy to share states across many components. It can exist in a separate JS file. To create a store, just wrap writable around a value.

In a component, we prefix store names with a $ in order to directly use or update them. Compiler magic!

Reactive State "Store"

9 - Conditional Rendering And Lists

We can conditionally render elements with Svelte's template via {#if} and optionally {:else}.

To render everything in a list, we have {#each}.

Remember to always close a block with {/if} or {/each}!

(Should've used <ol> in the example, but I wanted to show how index- access works.)

Conditional Rendering And Lists

10 - Elegant Async/Await

It's super easy to do asynchronous stuff like API requests with Svelte.

We can simply {#await} a Promise to resolve, displaying a "loading" placeholder before the result is ready.

Note that we await the Promise in the template section, so no await keyword in <script>.

Elegant Async/Await

BONUS - Animated Transitions

Svelte comes with neat animated transitions built-in. Try giving your components a transition:fly property! There're also other types like fade, slide, etc. You can also use in: out: to separately define intro/outros.

Attached to the transition prop are the params.

👆 That's All, Folks!

That's it - everything you need to get started with Svelte! 😁

We covered a lot in this crash course, from the most fundamental concepts to topics that might even be considered intermediate or advanced in other frameworks (eg. API requests and animated transitions).

Now it's your turn to play with Svelte and build something cool. The Svelte REPL is a great place to start!

Have fun! 🥳

(Thread crash course format inspired by @chrisachard 😁 Check out his excellent React/Redux, Git crash courses!)

PS

Because Svelte is so expressive, I joked the other day that Svelte devs count "characters of code", instead of "lines of code"...

True that! Here are a few tweet-sized Svelte applets Tomasz Łakomy (@tlakomy) and I (@hexrcs) have been playing with -

Liquid error: internal

So, what's the most complex Svelte app that we can fit in a tweet? 😁

 

Like this post?

I'll be posting more on Twitter: @hexrcs
You can also find me at my homepage: xiaoru.li

Top comments (28)

Collapse
 
mauro_codes profile image
Mauro Garcia

OMG! This post was amazing! After finishing the official Svelte tutorial, I can tell that you managed to cover many important topics with very few words!

Thanks! We need to start talking more about Svelte and the message behind the framework

Collapse
 
hexrcs profile image
Xiaoru Li

Thanks a lot for the kind words! Glad you liked it! 😄

More Svelte users, better ecosystem 😄

Collapse
 
rdewolff profile image
Rom

Very nice visuals! That help a lot to grasp the concept you explain very quickly! Great job!

Collapse
 
hexrcs profile image
Xiaoru Li

Thanks! 😁

Collapse
 
dmitrykurmanov profile image
Dmitry Kurmanov

Hello! Thanks for the great article!

If I understand correctly, there is a typo here.

I think that "Setting a prop is just like doing regular HTML." should be "Setting a prop is just like doing regular JS".

Collapse
 
hexrcs profile image
Xiaoru Li

Hi, it's actually not a typo. What I meant was setting props in regular HTML <img alt="Nice image" src="nice-img.jpg"> (image tag with alt and src prop/attribute) is exactly the same in Svelte's template.

Collapse
 
dmitrykurmanov profile image
Dmitry Kurmanov

I've got it.Thanks!

Collapse
 
cameronapak profile image
cameronapak

Thanks for creating this post! Reactive Statements remind me of the useEffect hook in React

Collapse
 
hexrcs profile image
Xiaoru Li

Yes! But if you are using it to set derived states, you don't have to specify the dependencies manually.

Collapse
 
seanmclem profile image
Seanmclem

Could you elaborate on setting props, in example 5? You export dark, so you can set it? But you set color, not dark. It's the one thing I don't understand

Collapse
 
hexrcs profile image
Xiaoru Li • Edited

Thanks for asking, I see I should have made it more clear there.

So we are dealing with 2 components here, a simpler component CoolDiv.svelte (whose code is not shown), and the component we are looking at. Let's say it's called CoolDivWithText.svelte. All the code shown here belongs to CoolDivWithText.svelte.

The dark prop is on CoolDivWithText while color prop is on CoolDiv. CoolDivWithText wraps around CoolDiv; instead of offering arbitrary color options, we limit it to only allow dark theme or bright theme.

(I'm thinking of remaking this example)

Edit: I've updated the image in the article. Here is the original one this comment was talking about.

Collapse
 
seanmclem profile image
Seanmclem

I'm just totally new to Svelte, but I really like this approach to crash-course.

Thread Thread
 
hexrcs profile image
Xiaoru Li • Edited

Glad you liked it! I'm also working on a GraphQL crash course, which I will publish soon.

I updated the 5th pic, by the way. Hopefully, it's less confusing this time.

Sometimes we can become biased and miss the readers' point of view. It's hard to unlearn stuff. 😛 Thanks for pointing it out!

Collapse
 
pavelloz profile image
Paweł Kowalski

Great work! Best presentation of the "get started with svelte" ive found on the internet. Congrats :)

Collapse
 
hexrcs profile image
Xiaoru Li

Awe, thanks so much!

Collapse
 
adityapadwal profile image
Aditya Padwal

Das ist toll!
Nice read.

It would be great to have you join the Svelte JS developers group on LinkedIn.

linkedin.com/groups/10473500

Collapse
 
hexrcs profile image
Xiaoru Li

Thanks, joining the group! (I'm not very active on LinkedIn though 😛)

Collapse
 
yarmaa profile image
Yarmaa

Thanks, this article is exactly what I was looking for :)

Collapse
 
ferhatavdic profile image
FerhatAvdic

Its a hot topic lately but it doesnt bring anything significant to the table.

Collapse
 
hexrcs profile image
Xiaoru Li

Speed, fully reactive state management, much smaller bundle size, write less code to do more? 😉

Collapse
 
ferhatavdic profile image
FerhatAvdic

Yes. Thats what we already have with the popular frameworks.

Aside from that i appreciate you trying it out and letting us know what it can do.

Thread Thread
 
jligeza profile image
Jakub Ligęza • Edited

Svelte has very good performance. If somebody wanted to make a hybrid app, this framework is a strong pick, as hybrid apps with popular frameworks often have visible performance issues.

Collapse
 
dennisfrijlink profile image
Dennis Frijlink

This the tutorials I like. Short, clean and most important, useful!

Collapse
 
bw984 profile image
Brady Walters

Great write up. This should be considered the pre-tutorial. A nice 10,000ft view before diving into the nitty gritty.

Collapse
 
bscott profile image
Brian Scott

This was an awesome post!!, wish I learned everything this way. Perfect crash course!

Collapse
 
oreadweb profile image
oRead

Svelte is very appealing but what about meta data?

Some comments may only be visible to logged-in visitors. Sign in to view all comments.