OJ Develops

Thoughts on software development. .NET | C# | Azure

Svelte Overview

25 February 2022

About Svelte

Svelte is a JavaScript framework that is used to build web applications.

These are the primary differences between Svelte and the “big three” (React, Angular, and Vue):

  • No runtime. Svelte compiles your components into code that is readable by the browser. Because of this, there is no need for a runtime that interprets or translates your code while the application is running.
  • No virtual DOM. This is related to the previous point about Svelte compiling your components into browser-readable code. When the code is compiled, it will already use the native DOM API to do DOM updates. There is no need for a separate virtual DOM that sits in between your code and the actual DOM.
  • Less syntax and framework API. The HTML, CSS, and JS code inside .svelte files look very similar to plain HTML, CSS, and JS. This makes it very easy to pick up for those who are new to front-end development. Ultimately, it takes less code in Svelte to achieve the same functionality that would take more code in other frameworks.

Trying Svelte

Try online

To try Svelte online, you can go to their website, specifically to the REPL page:

https://svelte.dev/repl

You will see two panes on that page. The left pane is what you would write inside a .svelte file. The right pane is what the result would look like.

Try locally with Visual Studio Code

Setup instructions:

  1. Install the Svelte Visual Studio Code Extension at https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode
  2. Install node, or optionally upgrade it to a newer version.

To create a new project, run the following commands:

npx degit sveltejs/template my-svelte-project
cd my-svelte-project
npm install
npm run dev

Svelte Snippets

Displaying the value of a variable

<script>
    let greeting = 'World';
</script>

<div>Hello {greeting}</div>

Looping through an array

<script>
    let products = [
      {
          id: 1,
          name: 'Product A'
      },
      {
          id: 2,
          name: 'Product B'
      }
    ];
</script>

<ul>
  {#each products as product}
      <li>{product.id}: {product.name}</li>
  {/each}
</ul>

Conditional rendering (if else)

<script>
    let number = 42;
</script>

{#if number > 10 }
    <div>The number is big.</div>
{:else}
    <div>The number is small.</div>
{/if}

Event handling

<script>
    function clickHandler() {
        alert('button was clicked')
    }
</script>

<button on:click={clickHandler}>My Button</button>

Input binding

<script>
    let name = 'John';
</script>

<input bind:value={name} />