22 September 2023
Svelte.js has quickly become one of the most popular open-source JavaScript frameworks. This progressive framework stands out for its high performance and small bundle sizes. By converting components into highly optimized vanilla JavaScript at build time, Svelte achieves better performance than traditional frameworks that interpret code at runtime.
This article can be used as support material for our delegates who are on our Svelte.js training course the perfect opportunity to train for you or your team. To find out more please feel free to get in contact.
In this comprehensive guide, you'll learn how to build a full-stack web application using Svelte from start to finish. We'll cover key concepts like components, routing, state management, and authentication. You'll gain hands-on experience setting up a Svelte development environment, building reusable components, integrating APIs, and deploying to production. Follow along to level up your Svelte skills!
Before diving into building an app, let's start with an overview of Svelte itself.
Svelte is a component framework that runs in the browser rather than relying on a virtual DOM. During the build process, your Svelte components are converted into tiny, highly optimized vanilla JS modules. This results in faster rendering and smaller bundle sizes.
Some of the key benefits of using Svelte include:
By learning Svelte, you can build incredibly fast web apps with excellent user experiences. It's one of the best frameworks for crafting high-performance frontend applications.
To build apps with Svelte, you'll need a basic understanding of the following:
You'll also want to have Node.js and npm installed locally. Optionally, an IDE like VS Code will be helpful for editing code.
With those basics covered, you're ready to start using Svelte to develop web applications. We'll explain other concepts along the way.
Let's get your environment configured for developing with Svelte. We'll install Svelte globally, generate a new project, examine the directory structure, install dependencies, and start up a dev server.
We first need the Svelte CLI, which is available as an npm package. Open up your terminal and enter:
npm install -g svelte
This installs the svelte
command globally, allowing you to generate new projects and compile Svelte code from the command line.
Use the svelte
command to generate a new project skeleton:
svelte new my-svelte-app
This creates a my-svelte-app
directory with starter code for an app. Navigate into this directory to continue setting up your environment.
The generated app contains the following key files and directories:
public/
- Static assets like index.html
and global stylessrc/
- Svelte component filesrollup.config.js
- Module bundler configurationpackage.json
- Dependencies and scriptsThis gives you a standard project layout optimized for Svelte.
Svelte apps rely on a few core packages to add functionality like routing and state management. Install these by running:
npm install
The key Svelte-related dependencies added are:
Finally, start up the local dev server with:
npm run dev
This compiles your app and serves it at http://localhost:5000
. Visiting this URL will display your running Svelte app, which you can now develop further.
With your environment set up, you're ready to build your first Svelte components!
Components are the building blocks of Svelte apps. Let's explore how to create and use Svelte components.
A component is a reusable self-contained module, similar to a JavaScript function. To define one, create a .svelte
file like:
<!-- src/Hello.svelte --> <script> // logic goes here </script> <h1>Hello World!</h1> <style> /* styles go here */ </style>
This single file contains the component markup, logic, and styles. You can import it anywhere in your app.
Svelte introduces some unique shortcuts for declaring components:
<script>
- For JavaScript logic and importing other modules<style>
- For scoped component CSS{expressions}
- Insert values into markupon:event
- Declare event handlersbind:prop
- Bind to component props$store
- Access store valuesThese features streamline building encapsulated components.
Let's build a reusable <Button>
component:
<!-- src/Button.svelte --> <script> export let text; function handleClick() { alert('Button clicked!'); } </script> <button on:click={handleClick}> {text} </button> <style> /* button styles */ </style>
We can import this anywhere and customize the text
prop:
<script> import Button from './Button.svelte'; </script> <Button text="Subscribe" />
This separates our presentation logic into reusable pieces.
Svelte components fire events on creation, update, and destruction:
onMount
- When component is createdbeforeUpdate
- Before component updatesafterUpdate
- After component updatesonDestroy
- When component is removedFor example, to run logic when a component mounts:
<script> import { onMount } from 'svelte'; onMount(() => { console.log('Component mounted!'); }); </script>
Use lifecycle events to integrate with external logic and libraries.
Now you know how to build encapsulated, reusable components - the core of Svelte apps!
Let's explore how to handle navigation and routing in a Svelte application. We'll use the SvelteKit framework for setting up routes and endpoints.
Routing allows you to:
Add SvelteKit to your project with:
npm install -D @sveltejs/kit
This provides functions for routing, server endpoints, and more.
SvelteKit uses the src/routes
directory to define routes. Each .svelte
file becomes a webpage route:
src/routes/ - index.svelte -> '/' - about.svelte -> '/about' - blog/[slug].svelte -> '/blog/:slug'
Navigate between pages by importing page
from SvelteKit and pushing new routes.
Routes like blog/[slug].svelte
with brackets create dynamic routes that accept parameters.
Access the params in the component with url.params
:
<!-- blog/[slug].svelte --> <h1>{url.params.slug}</h1>
This allows building routes like /blog/hello-world
.
Use the goto
function to navigate pages:
<script> import { goto } from '@sveltejs/kit'; function goToAbout() { goto('/about'); } </script>
SvelteKit provides functions like goto
, preload
, fetch
and more to control navigation.
With SvelteKit integrated, you can build multi-page app workflows with ease!
For managing data throughout components, Svelte provides built-in state management with stores. Let's see how we can use stores to share state.
Stores contain values that can update reactively. Define stores by importing writable
from 'svelte/store':
// store.js import { writable } from 'svelte/store'; export const count = writable(0);
This creates a store named count
with an initial value of 0
.
In Svelte components, import the store and use the $
prefix to access its value:
<script> import { count } from './store.js'; </script> <h1>Count: {$count}</h1>
Svelte will automatically re-render the component when the store value changes.
To modify stores, access its set
and update
methods:
count.update(n => n + 1); // Increment count
This allows sharing state between components reactively using stores.
Let's explore how to implement user authentication in a Svelte app, including login, protected routes, and managing state.
For authentication, we'll use an external library like svelte-auth.
Add svelte-auth with:
npm install svelte-auth
Then import it in your app.
Call authenticate
and logout
to sign users in and out:
import { authenticate, logout } from 'svelte-auth'; authenticate('credentials'); // logs user in logout(); // logs user out
Store the user data in a writable store on login.
Wrap routes in the Authenticated
component to check auth:
<Authenticated> <Route path="/settings" component={Settings}/> </Authenticated>
This redirects unauthorized users.
When the auth state changes:
This allows you to add full user authentication flows to your Svelte apps!
Let's explore how to build a production-ready Svelte application and deploy it for others to use.
For production builds, Svelte provides the svelte-kit build
command. This:
Set import.meta.env.MODE
to production
Run the production build with:
svelte-kit build
This outputs an optimized version of your app in build/
.
There are a few options for deploying your app:
build/
folder to a platform like Vercel or NetlifyChoose whichever hosting method best suits your stack and needs!
With that, you're ready to ship your Svelte creation to the world!
Congratulations, you've built an entire full-stack web application with Svelte!
Here are some key takeaways:
To continue learning Svelte:
Svelte makes it easy to build super fast web apps. Now put your skills to work on your own Svelte projects!
Here are answers to some common questions about Svelte development:
How does Svelte compare to React or Vue?
Svelte has performance advantages because it compiles away abstraction layers like the virtual DOM. It also includes features like reactivity out of the box. However, React and Vue have larger ecosystems currently.
Can I use TypeScript with Svelte?
Yes, Svelte fully supports TypeScript for those who prefer typed languages. Just rename files to .svelte.ts
.
Does Svelte work with frontend frameworks like Tailwind CSS?
Absolutely! You can incorporate any CSS framework into Svelte projects and use those styles within your components.
Can I make mobile apps with Svelte?
Svelte Native allows you to build mobile apps for iOS and Android using Svelte. There are also tools for building mobile web apps with Svelte.
Is Svelte good for big enterprise applications?
Svelte's great performance along with capabilities like code splitting make it well-suited for large, complex enterprise apps and internal business tools.
And there you have it - a comprehensive guide to building full-stack apps with Svelte step-by-step!
As mentioned at the start of the article JBI Training offers a fully comprehensive course in Svelte.js part of our resources include blog articles and how to guides including our previous article Getting Started with Svelte.js: A Beginner's Guide
or consider one of our other training courses.
Here are some other JBI Training courses that relate to building full-stack Svelte applications:
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