CUSTOMISED
Expert-led training for your team
Dismiss
Getting Started with Svelte.js: A Beginner's Guide

21 September 2023

Getting Started with Svelte.js: A Beginner's Guide

 

File:Svelte Logo.svg - Wikipedia

Are you looking to build fast, efficient web apps without the overhead of traditional frameworks? If so, Svelte.js may be the tool for you. Svelte is a new framework that compiles your components into highly optimized vanilla JavaScript. Instead of using a virtual DOM like React or Vue, it updates the DOM at compile time for blazing fast performance.

In this comprehensive guide, we'll walk through the key concepts and syntax of Svelte to help you get up and running. We'll compare it to other frameworks, explain the templating syntax, demonstrate reactivity and bindings, and much more. Follow along as we build a simple example app while covering the core ideas you'll need to start building Svelte applications.

This guide is intended to be used alongside JBI Trainings Svelte.js course

What is Svelte?

Svelte was created by Rich Harris and released in 2016. But it didn't gain widespread popularity until version 3 was released in 2019. Svelte is a component framework that runs at build time rather than runtime. When you create a component, Svelte compiles it into tiny, highly optimized vanilla JavaScript with just the code needed for that component.

This leads to much faster performance, lower memory usage, and smaller bundle sizes compared to alternatives like React, Vue, and Angular. Svelte also gets rid of the virtual DOM which simplifies debugging and allows advanced optimizations.

So in summary:

  • Svelte is a compiler that converts components into vanilla JS
  • It runs at build time rather than runtime
  • Features include high performance, smaller size, and reactivity
  • No virtual DOM overhead leading to better efficiency

Let's now look at why you might choose Svelte over other web app frameworks.

Why Use Svelte?

There are a few key advantages that make Svelte stand out from traditional frameworks:

  • Production code is highly optimized - Since compilation happens at build time, a lot of overhead can be stripped away and unused code removed. This results in much smaller bundle sizes.
  • Reactive programming model - Svelte uses a simple declarative syntax to create reactive components that update automatically. Less boilerplate code is needed compared to manually managing state.
  • No virtual DOM - Virtual DOMs have some performance overhead and complexity. Svelte updates the real DOM directly leading to better efficiency.
  • JSX is optional - You don't have to use JSX and can write HTML directly in your components. This is more approachable for some developers.
  • Great documentation - Svelte has excellent docs and tutorials making it easy for beginners to pick up compared to other new frameworks.

For an efficient and lightweight web app framework without the overhead of a virtual DOM, Svelte is a great choice. Next up, we'll get Svelte installed and configured on our machine.

Getting Set Up with Svelte

To start using Svelte, we first need to make sure we have Node.js and npm installed. Download and install the latest LTS version of Node.js which includes npm.

We can then install the Svelte CLI which will help create new projects and compile our app. Open a terminal or command prompt and enter:

npm install -g svelte

This installs the svelte CLI tool globally on our machine.

Next, we can use it to generate a new project by typing:

svelte new svelte-app

This will create a new folder named svelte-app and install the required dependencies. Navigate into this project folder and run:

cd svelte-app
npm run dev

This will compile and serve our app on http://localhost:5000. We're ready to start coding!

Open the project in your text editor of choice. I'll be using Visual Studio Code. The main files and folders you'll work with are:

  • src/main.js - Entry point that renders the Svelte app
  • src/App.svelte - Root Svelte component
  • public/ - Static assets like images
  • src/ - Where we'll add more Svelte components

Now let's create our first component!

Writing Your First Svelte Component

Components are the building blocks of Svelte apps. They are small reusable units that encapsulate markup, styles, and behavior.

Let's create a new component called Hello.svelte in the src folder. Add the following code:

<!-- Hello.svelte -->

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

<h1>Hello {name}!</h1>

<style>
  h1 {
    color: purple;
  }
</style>

Save the file then look at http://localhost:5000. You should see the heading rendered.

Breaking down the component syntax:

  • <script> - Declare JS logic like variables
  • <h1> - Markup and HTML goes here
  • {name} - Insert values with curly braces
  • <style> - Add CSS styling rules

Now import the component into App.svelte so it renders:

<script>
  import Hello from './Hello.svelte'; 
</script>

<main>
  <Hello />
</main>

Our Hello component is complete! Next let's look at Svelte's powerful reactivity system.

Understanding Reactivity in Svelte

A key feature of Svelte is its built-in reactivity for declarative programming. This allows components to automatically update the UI when underlying data changes.

For example, if we update the name variable in our component:

let name = 'world';

function updateName() {
  name = 'Svelte';  
}

The DOM will refresh to say "Hello Svelte!" when we call updateName().

We declare reactive statements using the $: syntax:

// reactive declaration
$: doubled = count * 2;

// reactive assignment 
$: {
  console.log('count is now ' + count);
}

Any variables referenced will cause updates when they change. This eliminates boilerplate code needed in other frameworks to manually handle state.

Some other reactivity features are:

  • Stores - State containers that components can subscribe to
  • Derived values - Create values derived from other reactive values
  • Context - Pass data implicitly to descendant components

We'll demonstrate more examples of reactivity as we build our sample app.

Using Conditionals in Svelte

To control the flow of our app, we'll need to use conditional logic like if/else statements. Here's how that works in Svelte:

<!-- Show welcome message if user is logged in -->
{#if user}
  <h2>Welcome back {user.name}!</h2>   
{:else}
  <p>Please log in</p>
{/if}

<!-- Check equality -->
{#if x === y}
  <p>{x} is equal to {y}</p>
{/if}

<!-- Multiple conditions -->   
{#if x > 10 && y < 5}
  <p>x is greater than 10 and y is less than 5</p>
{:else if x > 5 || y < 10}
  <p>x is greater than 5 or y is less than 10</p>
{/if}

Some points:

  • Use if and else blocks to conditionally render content
  • Braces { } indicate blocks
  • === checks equality while == checks value
  • && and || provide AND/OR logic

Conditionals are a critical part of building any app's logic. Next up, we'll look at looping over lists of data.

Rendering Lists with #each Blocks

To display collections of data, we can loop over the items using Svelte's built-in #each directive.

For example, to render an array of todos:

<!-- Loop over todos -->
<ul>
{#each todos as todo}
  <li>{todo.text}</li>   
{/each}
</ul>

<!-- Else show message -->  
{#each todos as todo}
  <p>{todo.text}</p>
{:else}
  <p>No todos found</p>
{/each}

When you need to loop over elements, use the #each block. Some key points:

  • as keyword gives the iteration variable a name
  • Can render {:else} case when array is empty
  • Items must have unique key attributes
  • Can destructure objects like {todo} too

Next let's see how events are handled in Svelte apps.

Handling Events in Svelte Components

To make our apps interactive, we need to be able to respond to user events like clicks, mouseover, key presses, and more.

In Svelte, we use directives like on:click to listen to events:

<button on:click={handleClick}>
  Click Me
</button>

<script>
  function handleClick() {
    alert('Button clicked!');
  }
</script>

Some common events you can listen for are:

  • on:click - Mouse clicks on a button or element
  • on:submit - Form submitted
  • on:input - Text input field changed
  • on:keydown - Key pressed on keyboard

Event modifiers like once, preventDefault, and stopPropagation are also available.

Now let's send some network requests to fetch data.

Making API Requests in Svelte

To get data from a server, we'll use the browser's built-in fetch method along with async/await:

<script>
  // Fetch JSON placeholder data
  async function getData() {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const data = await response.json();

    console.log(data);
  }
</script>

Some points on making API requests:

  • Use fetch to make network requests
  • await waits for promises to resolve
  • Handle errors and loading states
  • Useful libraries like axios also work

Async operations open up many possibilities like searching, loading feeds, user auth, and more.

Let's learn how components communicate before we build an API-driven app.

Passing Data Between Components

For our components to work together, we need to pass data between the parent and children. The main ways to do this in Svelte are:

Props

Props allow a parent component to pass data down to a child:

<!-- Parent.svelte -->
<Child name="John" />

<!-- Child.svelte -->
<script>
  export let name;
</script>

<h2>Hello {name}!</h2> 

Context

Context provides a way to share data down the component tree implicitly:

<!-- Provider component -->
<Context.Provider value={{user}}>
  ...
</Context.Provider>

<!-- Nested child component -->   
<script>
  import { Context } from './Context.svelte';

  const user = Context;
</script>

Stores

Stores allow components to subscribe to global state objects. Useful for things like authentication and UI state.

Now that we can pass data around, let's add some transitions and animations.

Animations and Transitions

To create sleek interfaces, Svelte makes it easy to animate elements as they enter, leave, or update. Let's look at a fade transition:

<!-- When this component enters/exits -->
{#key fade}
  <p transition:fade>Fades in and out</p> 
{/key}

<!-- On mount/unmount -->
<p 
  in:fade
  out:fade
>
  Fades
</p>
<!-- CSS transition -->
<style>
fade {
  transition: opacity 0.3s ease; 
}
</style>

Some types of transitions:

  • fade - Transition opacity
  • slide - Slide in/out
  • scale - Grow or shrink elements
  • And many more like zoom, draw, fly, etc.

Animations make apps feel polished and responsive.

Building a Svelte Todo App

Now let's put all these concepts together to build a simple todo app. It will:

  • Fetch todos from the JSONPlaceholder API
  • Allow adding/completing todos
  • Show loading and error states
  • Transition list items

Project Setup

Run svelte new svelte-todo to generate a new app. Replace App.svelte with:

<!-- App skeleton -->
<script>
  import TodoList from './TodoList.svelte'; 
</script>

<main>
  <h1>Svelte Todo</h1>
  <TodoList />   
</main>

We'll build the TodoList component next.

Fetching Data

First we need to get the todo data by calling the API. Create TodoList.svelte:

<script>
  // Fetch todos
  async function getTodos() {
    const resp = await fetch('https://jsonplaceholder.typicode.com/todos');
    return resp.json();
  }

  let todos = [];

  getTodos()
    .then(data => {
      todos = data;   
    });
</script>

This will populate the todos array with the API data when the component mounts.

Displaying Todos

Let's display the todo list, loading state, and errors:

<!-- Show loading text -->
{#if todos.length === 0}
  <p>Loading todos...</p> 
{/if}

<!-- Display error -->
{#if error}
  <p>Error loading todos</p>   
{/if}

<!-- List todos -->
{#if todos.length > 0}
  <ul>
    {#each todos as todo}
      <li>{todo.title}</li>
    {/each}
  </ul>  
{/if}

We check the length of the todos array to show the proper state.

Adding Todos

Let's add a form to allow creating new todos:

<form on:submit={addTodo}>
  <input bind:value={title}>
  <button>Add Todo</button> 
</form>

<script>
// ...

function addTodo() {
  todos = [...todos, {
    title,
    completed: false   
  }];

  title = '';
}
</script>

The new todo object is appended to the array. The input is bound to the title variable.

Transitions

For a nice touch, we'll animate new todos as they are added:

<!-- Animate new todos -->
{#each todos as todo, i (todo.id)}
  <li 
    transition:fly={{y: 200, duration: 400}}
    in:receive={{key: todo.id}}
    out:send={{key: todo.id}}
  >
    {todo.title}
  </li>  
{/each}

The fly transition animates the element flying in/out. Our app is complete!

Learning More and Next Steps

We've covered the core concepts and syntax of Svelte required to start building basic apps. Some next topics to learn are:

  • Stores - State management with global stores
  • Animations - Using transitions, keyframes, and timelines
  • Server-side rendering - Pre-rendering Svelte on the server
  • Testing - Unit testing components with the Svelte Testing Library
  • TypeScript - Using TypeScript for type safety
  • Deploying - Hosting Svelte apps on services like Vercel and Netlify

The Svelte documentation offers many additional guides and API references to go deeper. Real-world experience by building applications is also invaluable for cementing these concepts.

Some ideas for practice projects are:

  • A weather app using a weather API
  • An e-commerce site with products, cart, and checkout
  • A social media site with posts, comments, profiles, and feed
  • A chat or messaging app
  • A game with scores and leaderboards

The possibilities are endless! Svelte provides a fast and optimized framework for bringing your ideas to life. We encourage you to learn more with Svelte training articles, tutorials, and courses as you continue mastering Svelte.js.

Frequently Asked Questions

Here are some common questions about getting started with Svelte:

How do I add Svelte to an existing project?

You can install Svelte locally with npm install svelte and import it into your project. Or try SvelteKit for adding Svelte to Node.js projects.

What IDE is best for Svelte development?

Many popular code editors like VS Code, WebStorm, and Atom have good Svelte plugins available. Or try Svelte for VS Code.

Can I use TypeScript with Svelte?

Yes, Svelte has excellent TypeScript support. You can incrementally convert .svelte files to use TS by renaming them to .svelte.ts.

How do I test Svelte components?

The Svelte Testing Library is recommended for unit testing components. It allows simulating interactions and asserting on output.

What packages are commonly used with Svelte?

Some popular companion libraries are:

  • Svelte Material UI - Material Design components
  • Svelte Motion - Animation library
  • Svelte Router - Routing solution
  • Svelte Query - Fetching and caching data
  • SveltKIT - Framework for full web apps

I hope this provides the full Svelte beginner's guide article in HTML format. Let me know if you need me to make any changes or additions!

To continue your learning journey we would suggest training with JBI Trainings Svelte.js course or checking out our next article. 

CONTACT
+44 (0)20 8446 7555

[email protected]

SHARE

 

Copyright © 2024 JBI Training. All Rights Reserved.
JB International Training Ltd  -  Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS

Modern Slavery Statement & Corporate Policies | Terms & Conditions | Contact Us

POPULAR

Rust training course                                                                          React training course

Threat modelling training course   Python for data analysts training course

Power BI training course                                   Machine Learning training course

Spring Boot Microservices training course              Terraform training course

Kubernetes training course                                                            C++ training course

Power Automate training course                               Clean Code training course