1. javascript
  2. /frameworks
  3. /svelte

Introduction to Svelte - The Lightweight JavaScript Framework

Getting Started

The world of JavaScript frameworks — always evolving, and always captivating. Enter Svelte, a game-changing framework that's been making waves for a few years now, firmly on its way to bigger adoption.

Unlike its more prominent peers, such as React and Vue, Svelte brings a different approach to building web apps by shifting the work to the compiler.

We'll explore some of Svelte's unique features and advantages, and outline the potential of creating impressive web apps.

A Compelling Case: Why Svelte?

So, what sets Svelte apart from the rest? Well, the answer lies in its compiler. Instead of using a virtual DOM like other frameworks, Svelte compiles our components into efficient vanilla JavaScript during the build process. As a result, we get smaller bundle sizes and improved performance.

Moreover, Svelte's developer experience is delightful. With its simplified syntax, we can achieve similar functionality with leaner codebases.

The Prerequisites

Nothing is stopping us from just jumping into the setup. That's assuming we know the core concepts of JavaScript, as well as a basic understanding of HTML and CSS.

We suggest you spend some time brushing up on your JavaScript skills.

Also, before diving in, make sure you have Node.js installed. If you don't, you can download it from here.

Bear in mind that you might run into some problems with setup approaches that might be deprecated. To avoid that, refer to SvelteKit's guide to create a project.

For clarity purposes, we'll include the initial commands below.

npm create svelte@latest my-app
cd my-app
npm install
npm run dev

All of the dependencies in our apps will be bundled via Rollup.

Module Bundlers in JavaScript

The Basics of Svelte Components

As is the case in the other frameworks we covered, components are the building block of our web app. The same goes for Svelte. They're self-contained, reusable pieces of code that represent a part of the user interface we're going to build. We can start by observing a simple Svelte component called Greeting.svelte.

<!-- Greeting.svelte -->

<script>
  let name = "Developer";
</script>

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

As we can see, the component greets the user with a personalized message. Naturally, we can then open a separate App.svelte file, and import it there.

<!-- App.svelte -->

<script>
  import Greeting from "./Greeting.svelte";
</script>

<Greeting />

Data Binding and Interactivity

What is data binding? Simply put, we're referring to the process of syncing the data in our JavaScript code, with the HTML elements in the components we create.

This is a vital part of any web application, as it allows the user interface to stay up-to-date with the application's state. As for the developer experience, Svelte's data binding mechanism is smooth, easy to use, and quite intuitive.

<script>
  let name = " ";
</script>

<input type="text" bind:value="{name}" />

<p>Hello, {name}!</p>

Notice how we're binding the value attribute of the input element to the name variable. In this mock example, when the user types in the input field, the value of name is updated, and the paragraph updates in real time. There's no need for event listeners or manual updates as Svelte takes care of it all.

Adding Interactivity

Now let's add a dash of interactivity. With Svelte, it's quite straightforward to handle user interactions, such as clicks or key presses, with the on:eventname directive.

<script>
  let count = 0;

  function handleClick() {
    count += 1;
  }
</script>

<button on:click="{handleClick}">Click me!</button>
<p>You clicked {count} times.</p>

First off, we have a button that, when clicked, increments the counter. Then, the handleClick function is called when the button is clicked, and the paragraph element displays the updated count. Again, we can notice the simplicity and elegance of Svelte's approach to handling events.

State Management in Svelte

There's no doubt that our applications will grow more complex. Managing states will quickly become a critical task for us to focus on.

Svelte emphasizes simplicity and ease of use, even when it comes to state management. While other frameworks might require external libraries or convoluted patterns, in Svelte, we can turn to its built-in solution: the Svelte store.

Getting Acquainted with Svelte Stores

With Svelte stores, we have a neat way to manage the global state or share data between components. They're reactive, meaning that whenever the data in the store changes, all components that use the store are automatically updated.

// counterStore.js
import { writable } from "svelte/store";

export const counter = writable(0);
// Counter.svelte
<script>
  import { counter } from "./counterStore.js";

  function increment() {
    $counter += 1;
  }
</script>

<button on:click="{increment}">Increment counter</button>
<p>Global counter: {$counter}</p>

For instance, we can create a writable store called counter and import it into our Counter component. To access the store's value, we use the $ prefix, which also makes our component reactive to changes in the store. As the increment function updates the counter, the store will automatically display the updated value. The same goes for any other components we'll create.

Derived and Readable Stores

Aside from the writeable function, we can leverage other approaches such as derived and readable stores. They can help us manipulate data and respond to changes for different use cases that we may encounter.

Check out the official docs for a detailed overview

Routing in Svelte

Let's say we need to manage navigation between views in a single-page application. Now, Svelte doesn't include built-in routing functionality, but there are several choices we can turn to, as suggested in the official documentation.

Routing with Svelte-SPA-Router

The Svelte-SPA-Router is a hash-based, lightweight, routing library specifically tailored for Svelte applications. As an innovative option, we can leverage it to create SEO-friendly, static SPAs. Below, we can observe how a basic routing structure would look.

<script>
  import Home from "./pages/Home.svelte";
  import About from "./pages/About.svelte";
  import NotFound from "./pages/NotFound.svelte";

  const routes = {
    "/": Home,
    "/about": About,
    "*": NotFound,
  };
</script>

So, to navigate between these routes, we can use the link function provided by the library.

<!-- NavBar.svelte -->
<script>
  import { link } from "svelte-spa-router";
</script>

<nav>
  <a href="/" on:click="{link}">Home</a>
  <a href="/about" on:click="{link}">About</a>
</nav>

Feel free to explore more advanced features and options found in the official repository.

Something More Robust: Sapper and SvelteKit

Moving on, we have Sapper and SvelteKit as more powerful and feature-rich options for building Svelte applications. They include built-in routing, static site generation, as well as server-side rendering. But, Sapper is the older of the two, while SvelteKit is the evolution of it, developed by the same team behind Svelte.

When our project requires more advanced features and functionality, we should consider exploring these options. Keep in mind that they come with a steeper learning curve compared to using a simpler routing library like Svelte-SPA-Router.

Final Thoughts

Svelte's lightweight and efficient nature makes it an attractive choice for web engineers, regardless if you're just beginning your web development journey, or looking to switch up frameworks. By tinkering with its unique features and combining them with tooling from Svelte's eco-system, you'll have the potential to build modern, highly-performant web apps.

However, we've just scratched the surface of what Svelte can do. To dive deeper, check out the resources below, as well as some coverage on other modern-day frameworks.

Official Svelte documentation

Svelte tutorials and REPL download

Introduction to React

An Introduction to Next.js