Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 31, 2019 11:12 am GMT

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

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

Take frontend frameworks, for instance.

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

Still, we cant 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 dont know.

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

Heres what Im going to do:

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

Before getting all technical, heres a little context.

What is Svelte?

Svelte logo

Svelte is a components frameworklike React or Vue. But it comes with a twist.

Ive presented Svelte as new earlier, but its 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 projects ambitions:

In a nutshell?

Svelte runs at build time, relocating the work into a compile step that happens when building an app. Theres no virtual DOM and is, apparently, truly reactive.

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. Its also much more lightweight than Next.js.

Im ecstatic to get to play with it finally! Its 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, lets 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, its what makes web development so exciting, right? Theres 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 isnt really reactive and that its virtual DOM isnt 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 whats 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?

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

In last years 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, dont 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 its just fine. But to know which hats going to fit you, you need to try them.

And its 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 REPLa 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.sveltewe'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 OKa 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 me know!

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

First published on Snipcart's blog


Original Link: https://dev.to/couellet/svelte-3-tutorial-a-js-app-with-that-magic-framework-you-heard-about-1hkk

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To