21 September 2023
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
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:
Let's now look at why you might choose Svelte over other web app frameworks.
There are a few key advantages that make Svelte stand out from traditional 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.
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 appsrc/App.svelte
- Root Svelte componentpublic/
- Static assets like imagessrc/
- Where we'll add more Svelte componentsNow let's create our first 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 rulesNow 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.
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:
We'll demonstrate more examples of reactivity as we build our sample app.
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:
if
and else
blocks to conditionally render content{ }
indicate blocks===
checks equality while ==
checks value&&
and ||
provide AND/OR logicConditionals are a critical part of building any app's logic. Next up, we'll look at looping over lists of data.
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{:else}
case when array is emptykey
attributes{todo}
tooNext let's see how events are handled in Svelte apps.
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 elementon:submit
- Form submittedon:input
- Text input field changedon:keydown
- Key pressed on keyboardEvent modifiers like once
, preventDefault
, and stopPropagation
are also available.
Now let's send some network requests to fetch data.
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:
fetch
to make network requestsawait
waits for promises to resolveaxios
also workAsync 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.
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.
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 opacityslide
- Slide in/outscale
- Grow or shrink elementsAnimations make apps feel polished and responsive.
Now let's put all these concepts together to build a simple todo app. It will:
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.
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.
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.
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.
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!
We've covered the core concepts and syntax of Svelte required to start building basic apps. Some next topics to learn are:
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:
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.
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:
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
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