Skip to content

Svelte: A Revolution in JavaScript Frameworks

JavaScript frameworks have come a long way in the past decade. What started as simple libraries like jQuery has evolved into full-fledged frameworks like React, Vue, and Angular. These frameworks improved developer productivity and enabled building complex web applications. But they weren’t without tradeoffs. Large bundle sizes, overhead from abstraction, and intricate reactivity systems slowed down apps.

Enter Svelte – a new framework that flips the paradigm. Instead of interpreting your code at runtime, it compiles your components into highly optimized vanilla JS during the build step. This results in smaller bundle size, better performance and a refreshing developer experience. Read on as we explore what makes Svelte special.

What is Svelte Exactly?

Svelte is an open-source JS framework created by Rich Harris and maintained by the Svelte core team. Here are some of its highlights:

  • Compiles to Vanilla JS – No virtual DOM or abstraction layer. Your app is converted to plain JS, HTML and CSS during build.
  • Reactive Declarations – Declare reactive data with easy syntax. Svelte tracks dependencies and updates seamlessly.
  • Tiny Size – No overhead from virtual DOM and reactivity systems. Svelte apps are smaller and faster.
  • Component Focused – Components are the building blocks. Write encapsulated, reusable code with Svelte components.
  • HTML-based Syntax – Write Svelte like you would write HTML and CSS. Familiar syntax helps pick it up quickly.

So in summary, Svelte doesn’t power your app at runtime like other frameworks. It works during compile time to optimize your components into lean and mean vanilla JS. Your source code is converted into a highly performant web app.

How Svelte Compares to Other Frameworks

The unique compile-time approach of Svelte sets it apart from traditional JavaScript frameworks like React, Vue, and Angular. Let’s see how Svelte stacks up against them.

Svelte vs React

React popularized the component architecture and virtual DOM diffing for web apps. Svelte takes cues from it but also improves in several aspects:

  • No Virtual DOM – Reconciliation of virtual DOM in React has a run-time cost. Svelte avoids it with compile-time optimizations.
  • Better Readability – Svelte’s HTML syntax with embedded JS is more intuitive than JSX. Cleaner declarative code.
  • Size and Performance – No overhead from virtual DOM and other abstractions. Svelte apps are lighter and faster.
  • Reactivity Out-of-box – React uses external libraries for state management. Svelte bakes in reactivity with its syntax.
  • Learning Curve – React API and concepts like JSX, HOCs, Render Props have a learning curve. Svelte is relatively easier to grasp.

So while React ushered a component-driven approach, Svelte takes it further with its radical compiler and a friendlier syntax.

Svelte vs Vue

Vue simplified React by adopting a gentler learning curve and better docs. Svelte even manages to differentiate itself from Vue:

  • Reactivity – Vue uses observer pattern to track data changes. Svelte directly compiles declarative reactive statements.
  • Template Syntax – Vue tempates are HTML-like but use custom directive syntax. Svelte sticks closer to pure HTML.
  • Bundle Size – Vue’s reactivity system and runtime still adds bulk. Svelte shines here with its lean output.
  • Component API – Vue has a single file component spec. Svelte doesn’t force declarative format and gives more flexibility.

So Svelte borrows some great ideas from Vue like reactive declarations but again optimizes it further by compiling away abstractions into vanilla JS.

Svelte vs Angular

Angular is a “batteries-included” framework maintained by Google. It provides strong opinions about how to structure apps. Svelte differentiates itself with:

  • Size and Performance – Angular apps tend to be heavy with many libs. Svelte gives you only the bare minimum needed.
  • Complexity – Angular has a steep learning curve with TypeScript, RxJS, custom syntax etc. Svelte is designed for simplicity.
  • Syntactic Overhead – Angular’s template syntax is quite heavy and different from HTML/CSS. Svelte uses clean native web languages.
  • Bundle Size – Heavy use of RxJS, Zone.js and other libs bloat Angular apps. Svelte gives you only what you need.

The Angular approach of “batteries-included” means a large framework to learn and deal with. Svelte focuses on compiling away everything possible into tiny, fast and native code.

Diving Into Svelte: First Component

Now that we have an idea of how Svelte compares, let’s dive into the syntax by creating our first component:

<!-- Greeter.svelte -->

<script>
  export let name;
</script>

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

This is a component that accepts a name prop and renders a heading greeting the user. Notice how similar it is to a plain HTML file. We don’t need any build setup and imports to get started.

To use this component:

<!-- App.svelte -->
<script>
  import Greeter from "./Greeter.svelte";
</script>

<Greeter name="Svelte" />

And that’s it! The import syntax may remind you of frameworks like React. But under the hood Svelte converts this into plain custom elements that work across modern browsers.

Reactivity and State Management

A key part of building apps is managing state. Let’s see how reactivity works in Svelte:

<!-- Counter.svelte -->

<script>
  let count = 0;

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

<button on:click={increment}>
  Clicks: {count}
</button>

Here the count variable is declared as a let, which Svelte recognizes as a reactive declaration. Updating it automatically updates the UI. No getter/setter boilerplate needed!

Similarly, we can react to input events:

<!-- Form.svelte -->

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

<input bind:value={name}>

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

Two-way binding is directly baked into Svelte with the bind: directive. This leads to concise and declarative reactivity code.

For complex state management, Svelte integrates nicely with external stores like Svelte Store. So you get the best of both worlds.

Event Handling in Svelte

User interactions via events are central to UIs. Here’s how to handle them in Svelte:

<!-- ClickCounter.svelte -->

<script>
  let count = 0;

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

<button on:click={increment}>
  Clicked {count} times
</button>

Svelte uses on: directive as a prefix for event handlers. Note that we don’t need to worry about bind or context of this like in other frameworks. Svelte takes care of the details for us.

Event modifiers like once, preventDefault, stopPropagation etc. can be appended to the event name:

<form on:submit|preventDefault={handleSubmit}>

Svelte also supports event forwarding between components using createEventDispatcher. This enables creating custom events and Even-driven programming.

Building a To-Do App in Svelte

Let’s tie together the concepts we’ve learned by building a simple To-Do app. It will have:

  • An input to enter tasks
  • A submit button to add tasks
  • A list to display tasks
  • Checkbox to mark tasks completed

Here is the App component:

<!-- App.svelte -->

<script>
  import { onMount } from 'svelte';

  let tasks = [];
  let newTask;

  onMount(() => {
    // fetch stored tasks
  });

  function addTask() {
    tasks = [...tasks, { text: newTask, done: false }];
    newTask = '';
  }
</script>

<h1>My To-Dos</h1>

<input bind:value={newTask}>
<button on:click={addTask}>Add</button>

<TodoList {tasks}/>

It imports the TodoList component and manages the tasks array reactively using Svelte directives.

The TodoList component loops through the array to display tasks:

<!-- TodoList.svelte -->

<script>
  export let tasks;  
</script>

<ul>
  {#each tasks as task}
    <TodoItem {task}/>  
  {/each}
</ul>

Finally, the TodoItem component shows a task item with a checkbox:

<!-- TodoItem.svelte -->

<script>
  export let task;

  function toggleDone() {
    task.done = !task.done;
  } 
</script>

<li>
  <input type="checkbox" on:change={toggleDone} checked={task.done}>

  <span class:done={task.done}>
    {task.text}
  </span>
</li>

<style>
  .done {
    text-decoration: line-through;
  }
</style>

And that’s it! The full working app in ~100 lines of Svelte. No complex state management or reactivity logic needed. Just clean data flow between declarative components.

Building Realtime Apps with Svelte

Svelte not only makes reactive UIs easy but also simplifies realtime app capabilities like websockets.

Let’s make a multiplayer tic-tac-toe app. We’ll use Svelte with Pusher for realtime coordination:

<!-- Game.svelte -->

<script>
  import { onMount } from 'svelte';
  import { pusher } from './pusher';

  let board = Array(9).fill(null);

  const joinGame = async () => {
    //...init Pusher and presence channel
  };

  const makeMove = (square) => {
    //...broadcast move
  };

  onMount(async () => {
    await joinGame();

    pusher.subscribe(data => {
      board = data.board; // update board reactively
    });
  });
</script>

<!-- render board -->

<div class="square" on:click={() => makeMove(i)}>{board[i]}</div> 

Thanks to Svelte reactivity, we can directly update the board variable when receiving moves from other players via Pusher. The UI automatically updates in realtime without needing to manually reconcile a virtual DOM.

Svelte’s design makes features like realtime coordination almost transparent!

Advanced Svelte Features

We’ve covered the basics of Svelte components. Here are some more advanced capabilities:

Routing

Svelte apps can integrate routing using Svelte Router. It allows creating multi-page apps with navigable components.

// Router.svelte
import Router from 'svelte-router';

const routes = {
  '/': Home,
  '/about': About
};

<Router {routes}/>

Animations and Transitions

Svelte elements can animate when added/removed from the DOM using transition: and @keyframes:

{#if visible}
  <div transition:fade>
    fades in and out
  </div>  
{/if}

SSR and SSG

Svelte apps can leverage SSR via SvelteKit. It sets up routing, pre-rendering and code splitting baked-in:

// src/routes/+page.svelte

<h1>Welcome</h1>

This allows building sites using Svelte instead of just SPAs.

TypeScript Support

Svelte has first-class support for TypeScript. Just use the .svelte filetype:

<script lang="ts">
  let name: string;  
</script>

CSS/SCSS Modules

Svelte CLI supports CSS modules and preprocessors like SASS out-of-the-box. Styles become scoped and reusable across components.

Component Libraries

Share common UI elements as Svelte component libs like Svelte Material UI. This enhances consistency and reusability.

These advanced features combined with Svelte’s performance opens doors for all kinds of web apps.

Optimizing Svelte App Performance

A key benefit of Svelte is smaller bundle size and faster performance. Here’s how the Svelte compiler optimizes your app:

  • Tree Shaking – Only includes code used by your app, removing unused module exports etc.
  • Code Splitting – Divides bundle into lazy-loaded chunks to reduce initial load size.
  • Minification – Mangles variables, removes comments and whitespace etc. to reduce file size.
  • No Abstraction Penalty – No virtual DOM diffing, observables or proxy objects. Plain JS executes faster.

For further optimization, you can:

  • Svelte Preprocess – Use this plugin to strip unused CSS and minify HTML during build.
  • Webpack – Fine-tune the Svelte webpack config for code splitting, lazy loading etc.
  • SvelteKit SSR – Use SvelteKit’s SSR and hydration for faster initial page loads.
  • Svelte Native – For mobile apps, Svelte Native compiles to native UI code avoiding JavaScript bridge costs.

So while Svelte gives great performance out-of-the-box, further tweaks to your bundler config and build pipeline can enhance it even more.

Real-world Use of Svelte

While newer than alternatives, Svelte adoption has been rapid among developers and companies. Here are some notable examples:

  • The New York Times – Migrated their comment section from React to Svelte resulting in 50% bundled size reduction.
  • Discord – Used Svelte to revamp their onboarding and account creation flows across web and mobile for a buttery-smooth UX.
  • Razorpay – Rewrote their web dashboard from React to Svelte reducing bundle size by 65% and time-to-interactive by 40%.
  • Rakuten – Their Rakuten TV portal rebuilt in Svelte led to a 3x faster app with half the codebase.
  • Babylon Health – Babylon’s app backend dashboards use SvelteKit for easy development and SSR.

Svelte has proved effective for building highly interactive UIs as well as marketing sites. Its performance advantages can benefit diverse applications.

Getting Involved in the Svelte Community

As Svelte gains mainstream traction, so does its community. Here are some ways to connect with other Svelte users:

  • Discourse Forum – Ask questions and discuss Svelte with over 8K members. Highly active user community.
  • Reddit – The r/sveltejs subreddit has tips, showcases and announcements about the ecosystem.
  • Discord – Chat in realtime with fellow Svelte devs on the official Discord server.
  • Meetup Groups – Join local Svelte meetups and workshops to connect with users in-person.
  • Twitter – Follow and engage with the #sveltejs hashtag. Many core team members are active here.
  • Dev.To – Several Svelte bloggers post tutorials and guides on Dev.to regularly.
  • YouTube – Find video tutorials and conference talks about Svelte from community creators.

The friendly community makes it easy to learn Svelte and get answers to your questions from experienced users. The resources are sure to grow as Svelte gains adoption globally.

The Svelte Ecosystem: Integrations and Tools

Although not as mature as some alternatives, Svelte already has a rich ecosystem to enhance development: