Svelte 3 Tutorial: A JS App with That Magic Framework You Heard About

In a rush? Skip to tutorial or live demo.

Just when you were getting comfy with tools you love, something pops up, challenging everything you know.

Take frontend frameworks, for instance.

We’re 100% behind the paradigms React, Vue and others brought forth a few years ago.

Still, we can’t turn a blind eye to novel tools that are creating fresh ways to do frontend development.

And Svelte, a JS framework for “cybernetically enhanced web apps,” does just that.

cybernetically-enhanced-web-apps

Is it better than other frontend frameworks? I honestly don’t know.

But this Svelte tutorial is going to help me (and you!) better understand what it’s all about.

Here’s what I’m going to do:

  • Start a Svelte project
  • Write a simple markdown editor
  • Run it locally on my machine

Before getting all technical, here’s a little context.

What is Svelte?

Svelte logo

Svelte is a components framework—like React or Vue. But it comes with a twist.

I’ve presented Svelte as new earlier, but it’s been around since 2016. However, Svelte 3, released earlier this year, really pushed the framework to the web dev forefront.

Developed by Rich Harris, Svelte offers a new approach to building UIs. It rethinks the way popular frameworks like React and Vue operate.

In this video, Harris explains his project’s ambitions:

In a nutshell?

Much like React, Svelte also has its Next.js: Sapper. This application framework lets you build web apps of all sizes with built-in SEO and instantaneous navigation. It’s also much more lightweight than Next.js.

I’m ecstatic to get to play with it finally! It’s supposed to enable very performant apps and excellent developer experience.

It could be used as an alternative to Vue or React for future projects. But before I start building a Svelte demo app, let’s see how it compares to those two on paper.

Svelte vs React (& Vue)

Born inside Facebook in 2011, React made reactive programming very popular.

It quickly became the most popular frontend framework. It still owns the crown to this day.

Still, some developers keep asking: “How can we do better?” I mean, it’s what makes web development so exciting, right? There’s always a way to do better.

React was the first to use something called the virtual DOM. This concept abstracts out the attribute manipulation, event handling, and manual DOM updating that you would otherwise have to use to build your app. It was an essential part of what made React so attractive, for good reasons.

In the video above, Harris makes the case that React isn’t really reactive and that its virtual DOM isn’t fast enough. Svelte had to do things differently:

Svelte is a compiler; it compiles your components into JavaScript instead of relying on concepts like Virtual DOM to update your browser DOM. This boosts performance and brings true reactivity to your code.

This graph shows what’s going on under the hood for Svelte and React:

Svelte vs React explained - graph

Svelte 3 moves reactivity out of the component API and into the language.

It also results in a developer experience that feels closer to plain JS than working with other frameworks.

Is Svelte the next big thing?

Is Svelte bound to surpass Vue & React as the frontend framework of the future?

It’s hard to predict. As of today, it’s far from the level of popularity of its counterparts. It also doesn’t have big corporation backup like React, but then again, Vue did great without it.

In last year’s State of JS survey, which annually collects developers’ JS habits, Svelte appeared as the most popular of the other libraries category. It could be considered as one of the main JS frameworks sooner than later, though.

In the end, don’t think of Svelte as a replacement for other frameworks, but as an alternative to them. Some devs prefer working with one or the other, and it’s just fine. But to know which hat’s going to fit you, you need to try them.

And it’s time to do precisely that with Svelte!

Step-by-step Svelte tutorial: building a simple JS app

For this demo, we'll write a tiny application. My goal is to show how simple and quick it is to get started with Svelte.

Let's build a barebones, two-panels markdown editor.

Get started with Svelte

When starting a new Svelte project, it is recommended to use their REPL—a convenient tool to get started with the framework. But in "real life," you'll want to work in an editor such as VS Code. So open the REPL, and download the project locally:

Selvte REPL

Unzip the downloaded file and open a code editor at the root of the extracted folder. Your files structure should look like this:

Svelte files structure

In a Svelte project, you can use any NPM modules. Here we'll use the excellent Marked library, a markdown parser and compiler.

Open a terminal and install the package.

npm install marked

Create the component for your Svelte app

In your project, open App.svelte—we'll write our application in this component directly. To show how simple Svelte is, we'll write everything in this component. It's also possible to nest components, and it's straightforward. Read more about this in Svelte's documentation.

Start by removing the code in the <script> tag.

Then, import marked. In the <script> tag add this line on top:

import marked from 'marked';

We'll then need two variables, one containing the markdown text that will be compiled by marked and another containing the HTML compiled by the library.

let source = '# New document';
let markdown = marked(source);

Let's write the template. In the same file still, add these lines after the <script> block.

<header class="header">
    <h1 class="header-title">Svelte powered markdown editor</h1>
</header>

<div class="markdown-editor">
    <div class="markdown-editor__left-panel">
        <textarea class="markdown-editor__source"></textarea>
    </div>

    <div class="markdown-editor__right-panel">
        <div class="markdown-editor__output">{markdown}</div>
    </div>
</div>

Finally, we'll add some styles. In the same file, add a <style> block after the template.

<style>
    .header {
        height: 10vh;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .header-title {
        margin: 0;
    }

    .markdown-editor {
        width: 100%;
        display: flex;
        align-items:flex-start;
        justify-content: space-evenly;
    }

    .markdown-editor__left-panel, .markdown-editor__right-panel {
        width: 50%;
        border: solid 1px black;
        height: 90vh;
    }

    .markdown-editor__right-panel {
        overflow: auto;
    }

    .markdown-editor__source {
        border: none;
        width: 100%;
        height: 100%;
    }

    .markdown-editor__source:focus {
        outline: none;
    }

    .markdown-editor__output {
        width: 100%;
        padding: 0 2em;
    }
</style>

To make it look good, we'll need to clean the built-in CSS rules. In the project, you have a public folder. It contains the index.html file, which is the main layout file, along with some assets.

Open global.css, this is the file where all your global CSS rules will be. It's important to know that CSS rules specified in components directly will be scoped to the component itself.

Remove this CSS rule:

body {
    padding: 8px;
}

And add this one:

* {
    box-sizing: border-box;;
}

Now, in your terminal, run:

npm run dev

This will start your development server. Open a browser and go to localhost:5000.

Your app should look like this:

App first draft

There are still multiple issues, right? The markdown content stored in source variable isn't visible in the textarea, HTML is encoded in the output tab, and if you type anything in the textarea, nothing happens:

Nothing happens when I type

The first thing we'll solve is the markdown output. There's a special tag in Svelte that you can use: {@html ...}. This tag will make sure that the HTML is rendered directly in the component.

So in App.svelte, change:

<div class="markdown-editor__output">{markdown}</div>

by:

<div class="markdown-editor__output">{@html markdown}</div>

Now, if you refresh your app in your browser, it should look like this:

Markdown displayed correctly

But we still have a problem: the source variable isn't bound to the textarea. To do so, we'll need to add a binding:

<textarea  bind:value={source}  class="markdown-editor__source"></textarea>

Using the bind:value directly, we instruct Svelte that the value of this form element should be bound to our source variable.

Now, refresh the page, and you'll see that the textarea value is set properly:

Textarea value is set properly

Amazing! That should work, right? Start typing in the textarea:

Not reactive

Well, this is kind of disappointing. The reason it doesn't work is that the markdown variable we declared previously isn't reactive:

let markdown = marked(source);

To have a reactive property in Svelte, you have to use a special syntax. This is something you might never have seen before because Svelte is probably the only framework using it. We're going to use what they call a label in JavaScript. This unfamiliar syntax is perfectly valid JavaScript:

$: markdown = marked(source);

Now, refresh your browser:

Markdown editor works

So yeah, we built a simple markdown editor with three lines of JavaScript:

<script>
    import marked from 'marked';
    let source = '# New document';
    $: markdown = marked(source);
</script>

Pretty impressive, isn't it?

Live demo and GitHub repo

See the Github repo here.

See the live demo here.

Closing thoughts

Although I kept it very simple, I can see how robust this framework is. I can't wait to see how it'll evolve in the future.

My only "complaint" would be the lack of integrations with code editors. I'm a big fan of VS code and was a bit disappointed that there were some issues with Svelte extensions I found. You can set your syntax highlight to HTML, and it works OK—a Svelte component is literally an HTML file when you look at it. But it would be nice to get some autocomplete features and stuff like that. ;)

This demo took me ~10 minutes to write. Of course, this demo is elementary: a single component, three lines of JS. I can appreciate how inviting Svelte can be for web developers starting to dabble in frameworks.

I really suggest you watch the video we referenced at the beginning of this post!

As with any components framework, we could have used it to build a large application. I definitely like the way they designed their single-page components implementation. Nesting components is simple, and you get most of the features you have in React or Vue, for instance.

Have you tried Svelte? Will you? Let us know!


If you've enjoyed this post, please take a second to share it on Twitter. Comments, questions? Hit the section below!

Suggested posts: