The Svelte Handbook – Learn Svelte for Beginners

Svelte is a modern web development framework that has been rapidly growing in popularity. It takes a fresh approach compared to older frameworks like React and Vue, and provides a simpler yet powerful way to build user interfaces.

In this guide, I‘ll give you a thorough introduction to Svelte and walk you through the key concepts and features you need to know to start building web apps with it. By the end, you‘ll have a solid foundation in Svelte and be ready to tackle your own projects. Let‘s jump in!

What is Svelte?

Svelte is a frontend web framework, similar in many ways to React or Vue. It allows you to declaratively describe user interfaces using components, and automatically keeps the DOM in sync with your application state.

However, Svelte has a few key differences. Rather than shipping a runtime library to the browser to render the UI, Svelte is a compiler that converts your components to plain, vanilla JavaScript at build time. The result is much smaller bundle sizes and faster performance since the browser has less work to do.

Some other advantages of Svelte:

  • Simplified reactivity model compared to React or Vue
  • Uses standard HTML and CSS with minimal templating syntax
  • Scoped styles for components without extra tooling
  • Built-in transitions and animations
  • Supports TypeScript

Svelte has been growing quickly in popularity due to its ease of use, fast performance, and rich feature set. It powers many well-known sites including The New York Times, Spotify, Square, and Rakuten.

Getting Started with Svelte

The easiest way to start playing with Svelte is using the REPL (read-eval-print loop) on the official website at svelte.dev/repl. This provides an interactive playground where you can experiment without setting up a local development environment.

To develop locally, you‘ll need to have Node.js and npm installed. Then you can quickly scaffold a new Svelte project using one of the official templates. Run this command to set up a basic starter app:

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

This will create a new directory, install dependencies, and start a local development server. Open up http://localhost:5000 and you‘ll see your shiny new Svelte app running!

Svelte Components

Components are the building blocks of Svelte applications. Each component is defined in a .svelte file that contains the markup, styling, and behavior needed to render a piece of UI.

Here‘s a basic example of a Svelte component:

let count = 0;

function increment() {
count += 1;
}

button {
background: #ff3e00;
color: white;
border: none;
padding: 8px 12px;
border-radius: 2px;
}

This component will render a button that displays the number of times it has been clicked. Let‘s break it down:

  • The block contains JavaScript that runs when the component is initialized. Here we declare a count variable with an initial value of 0 and an increment function that will be called when the button is clicked.

  • The block contains CSS that is scoped only to this component. No extra build tools or libraries are needed for CSS scoping!

  • The markup section contains the actual HTML that will be rendered. The on:click syntax is how we bind the increment function to the button‘s click event. The {count} syntax allows us to embed dynamic values into the markup.

To use this component in another part of our app, we can import it into any other .svelte file:

import Counter from ‘./Counter.svelte‘;

Templating Syntax

Svelte templates support a variety of special syntax for embedding dynamic values and flow control into HTML:

  • {expression} for embedding any valid JavaScript expression
  • {#if expression} for conditionally rendering blocks
  • {#each array as item} for looping over arrays or iterables
  • {#await promise} for handling async values
  • on:eventname for listening to DOM events
  • bind:value for two-way binding of data

Here‘s an example showing some of these concepts:

let users = [];

async function getUsers() {
const res = await fetch(/users);
users = await res.json();
}

{#if users.length}

    {#each users as user}

  • {user.name}
  • {/each}

{:else}

{/if}

State Management

As we saw in the initial Counter component example, local component state can be managed by simply declaring JavaScript variables in the block, using the let keyword.

Svelte‘s reactivity system will automatically detect when these variables are updated and re-render the necessary parts of the component. In most cases, there‘s no need for explicit tracks of derived state like in React or Vue.

To share state between components, Svelte provides a store abstraction. Stores are simply objects that hold a value and allow multiple components to subscribe to changes.

Here‘s an example of using a store to share a count value across components:

import { writable } from ‘svelte/store‘;

export const count = writable(0);

import { count } from ‘./stores.js‘;

function increment() {
count.update(n => n + 1);
}


import { count } from ‘./stores.js‘;

function decrement() {
count.update(n => n – 1);
}


import { count } from ‘./stores.js‘;
import Incrementer from ‘./Incrementer.svelte‘;
import Decrementer from ‘./Decrementer.svelte‘;

The special $ syntax is used to reference the value of a store (e.g. $count). Whenever the store‘s value changes, any reference to it will be updated automatically. This allows the App component to react whenever Incrementer or Decrementer modify the shared count.

Lifecycle Hooks

Svelte provides a handful of lifecycle functions that allow you to run code at specific points in a component‘s lifecycle:

  • onMount – runs after the component is first rendered to the DOM
  • onDestroy – runs when the component is removed from the DOM
  • beforeUpdate – runs before the DOM is updated
  • afterUpdate – runs after the DOM is updated

A common use case for lifecycle hooks is fetching data or setting up event listeners when a component mounts. For example:

import { onMount } from ‘svelte‘;

let users = [];

onMount(async () => {
const res = await fetch(/users);
users = await res.json();
});

    {#each users as user}

  • {user.name}
  • {/each}

Here the onMount hook is used to fetch data from a /users API endpoint when the component first renders. The component will initially render with an empty users array, then re-render once the fetch completes and the users variable is populated.

Bindings

In addition to event handlers, Svelte components can also bind data to certain element attributes using the bind:attribute syntax.

This is commonly used for two-way binding of form elements:

let name = ‘‘;

Hello {name}!

Here the value of the input will automatically be bound to the name variable. Whenever the user types into the input, name will be updated, and vice versa.

Bindings can also be used to get references to DOM elements or component instances:

let buttonEl;

function handleClick() {
buttonEl.style.transform = translateX(${Math.random() * 100}px);
}

Slots

Slots allow you to define placeholder regions in a component that can be filled in with content when the component is used. This is useful for creating reusable layout or UI components.

For example, we could create a generic Card component that renders whatever content is passed to it:

.card {
border: 1px solid #ddd;
border-radius: 4px;
padding: 16px;
margin-bottom: 16px;
}

import Card from ‘./Card.svelte‘;

Hello

This is some card content.

Graph

This card contains an image.

The tag defines where content should be rendered within the Card. Multiple slots can also be defined using named slots:

Article Title

The article content

Read more…

Tooling and Deployment

The Svelte compiler is what powers a lot of the magic behind the scenes, analyzing your component code and converting it into plain JavaScript that can run in the browser.

A number of build tools can be used to bundle Svelte apps and run the compiler, including Rollup, webpack, and Parcel. The official Svelte template uses Rollup by default.

When it comes time to deploy your Svelte app to production, you‘ll first need to run the build command provided by your template:

npm run build

This will invoke the compiler to convert all your .svelte files to JavaScript and output them to a /public directory along with any other assets. The contents of /public can then be uploaded to any static web host, like GitHub Pages, Vercel, or Netlify.

Because Svelte compiles everything ahead of time, the production deployment contains zero framework code, just the components you‘ve authored. This results in extremely lean bundle sizes and fast load times.

Conclusion

Svelte is a powerful yet approachable framework for building web UIs. Its compiler-driven approach results in fast, lightweight apps without the overhead of a traditional runtime framework. Features like scoped styles, a simplified reactivity model and built-in transitions make it a joy to use.

In this article, we‘ve covered all the key concepts you need to get started building applications with Svelte, including:

  • Creating components with .svelte files
  • Templating syntax for dynamic data and flow control
  • Managing local state and shared state with stores
  • Lifecycle hooks for adding custom behavior
  • Bindings for form elements and DOM references
  • Slots for composing components
  • Compiling and deploying to production

To learn more, I highly recommend working through the Svelte tutorial and API docs. The community also maintains a number of frameworks and component libraries worth checking out like Sapper, SvelteKit, and Svelte Material UI.

Similar Posts