CUSTOMISED
Expert-led training for your team
Dismiss
Getting Started with Svelte.js: A Beginner's Guide

20 April 2023

Learn Svelte.js from Scratch: A Comprehensive Guide for Beginners

This article is brought to you by JBI Training, the UK's leading technology training provider.   Learn more about JBI's Python training courses including Python (Advanced), Python Machine Learning, Python for Financial TradersData Science and AI/ML (Python)Azure Cloud Introduction & DevOps Introduction

Step 1: Setting up the Development Environment

Before we start building our web application using Svelte.js, we need to set up our development environment. Here are the steps to follow:

  1. Install Node.js: Svelte.js is built on top of Node.js, so you need to install Node.js first. You can download the latest version of Node.js from the official website.

  2. Install a code editor: You can use any code editor to write your Svelte.js code, but we recommend using Visual Studio Code. It's a lightweight, open-source code editor that has many useful features for web development.

  3. Create a new Svelte.js project: Once you have installed Node.js and a code editor, you can create a new Svelte.js project using the degit tool

 Here are the links for the tools and resources mentioned in the guide:

  1. Node.js: https://nodejs.org/en/
  2. Visual Studio Code: https://code.visualstudio.com/
  3. degit: https://github.com/Rich-Harris/degit
  4. Svelte.js documentation: https://svelte.dev/docs
  5. Svelte REPL: https://svelte.dev/repl
  6. Svelte Starter Template: https://github.com/sveltejs/template
  7. Svelte Testing Library: https://testing-library.com/docs/svelte-testing-library/intro
  8. Svelte Store: https://svelte.dev/docs#svelte_store

I hope these links are helpful!

I apologize for the confusion. Here are the links for the tools and resources mentioned in the guide within the body of the article:

Step 1: Setting up the Development Environment

Before we start building our web application using Svelte.js, we need to set up our development environment. Here are the steps to follow:

  1. Install Node.js: Svelte.js is built on top of Node.js, so you need to install Node.js first. You can download the latest version of Node.js from the official website: https://nodejs.org/en/

  2. Install a code editor: You can use any code editor to write your Svelte.js code, but we recommend using Visual Studio Code. It's a lightweight, open-source code editor that has many useful features for web development. You can download Visual Studio Code from the official website: https://code.visualstudio.com/

  3. Create a new Svelte.js project: Once you have installed Node.js and a code editor, you can create a new Svelte.js project using the degit tool. You can install degit using Node.js by running the following command in your terminal:

 

npm install -g degit

After you have installed degit, you can create a new Svelte.js project by running the following command:

 

degit sveltejs/template my-svelte-project

This will create a new Svelte.js project in a directory called my-svelte-project.

  1. Learn the basics of Svelte.js: Before we start building our web application, we need to learn the basics of Svelte.js. You can start by reading the Svelte.js documentation: https://svelte.dev/docs

  2. Try the Svelte REPL: Svelte provides a REPL (Read-Eval-Print Loop) where you can experiment with Svelte code without setting up a project. You can access the Svelte REPL here: https://svelte.dev/repl

Now that we have set up our development environment and learned the basics of Svelte.js, we can start building our web application.

Step 2: Building a Simple Web Application

In this section, we will build a simple web application using Svelte.js. Our web application will display a list of items and allow us to add new items to the list.

  1. Open your Svelte.js project in your code editor.

  2. In the src directory, create a new file called App.svelte. This file will contain the code for our web application.

  3. In App.svelte, add the following code:

 

<script> let items = ['Item 1', 'Item 2', 'Item 3']; let newItem = ''; function addItem() { items = [...items, newItem]; newItem = ''; } </script> <h1>My List</h1> <ul> {#each items as item} <li>{item}</li> {/each} </ul> <input type="text" bind:value={newItem}> <button on:click={addItem}>Add Item</button>

Let's break down this code:

  • We define two variables: items and newItem. items is an array that contains the items in our list, and newItem is a string that represents the text of the new item we want to add to the list.
  • We define a function called addItem() that adds the newItem to the items array and then resets the newItem variable to an empty string.
  • We use the #each block to iterate over the items array and display each item in a list item (<li>).
  • We use the bind directive to bind the value of the newItem input element to the newItem variable.
  • use the on:click directive to add an event listener to the "Add Item" button that calls the addItem() function when clicked.
  1. In src/main.js, add the following code to render the App component:

import App from './App.svelte'; const app = new App({ target: document.body, }); export default app;

  1. Start the development server: To start the development server, run the following command in your terminal:

npm run dev

This will start a development server at https://localhost:5000. You can open this URL in your browser to view your web application.

  1. Test the web application: In your browser, you should see a heading "My List", a list of items, and an input field and "Add Item" button to add new items to the list. You can try adding new items to the list and see them appear.

Congratulations! You have built your first Svelte.js web application.

Step 3: Testing the Web Application

In this section, we will learn how to test our Svelte.js web application using the Svelte Testing Library.

  1. Install the Svelte Testing Library: You can install the Svelte Testing Library using npm by running the following command in your terminal:
 

npm install --save-dev @testing-library/svelte

  1. Create a new test file: In the src directory, create a new file called App.test.js. This file will contain the tests for our App component.

  2. In App.test.js, add the following code:

 

import { render, fireEvent } from '@testing-library/svelte'; import App from './App.svelte'; test('adds new items to the list', async () => { const { getByText, getByPlaceholderText } = render(App); // Find the input field and type a new item const input = getByPlaceholderText('Add new item...'); await fireEvent.input(input, { target: { value: 'New Item' } }); // Click the "Add Item" button const button = getByText('Add Item'); await fireEvent.click(button); // Check that the new item appears in the list getByText('New Item'); });

Let's break down this code:

  • We import the render and fireEvent functions from the Svelte Testing Library.
  • We import the App component from App.svelte.
  • We define a test case that checks whether a new item is added to the list when the "Add Item" button is clicked.
  • In the test case, we use the render function to render the App component.
  • We use the getByPlaceholderText function to find the input field and the fireEvent.input function to type a new item in the input field.
  • We use the getByText function to find the "Add Item" button and the fireEvent.click function to click the button.
  • We use the getByText function again to find the newly added item in the list.
  1. Run the tests: To run the tests, run the following command in your terminal:
 

npm run test

This will run the tests and output the test results in your terminal.

Congratulations! You have learned how to test your Svelte.js web application using the Svelte Testing Library.

Step 4: Working with the Svelte Store

In this section, we will learn how to use the Svelte Store to manage

The Svelte Store is a centralised state management system that allows us to share state between components in our web application. The Svelte Store consists of a single source of truth called the store, and any component that needs to access or modify the state can do so by subscribing to or updating the store.

Let's add a Svelte Store to our web application to manage the list of items.

  1. Create a new file called store.js in the src directory.

  2. In store.js, add the following code:

import { writable } from 'svelte/store'; export const items = writable([]);

Let's break down this code:

  • We import the writable function from the svelte/store module.
  • We create a new Svelte Store called items using the writable function.
  • The initial value of the items store is an empty array.
  1. Update App.svelte to use the items store:
  • Import the items store from store.js by adding the following code to the top of App.svelte:
 

import { items } from './store.js';

  • Replace the items array with the items store in the script section:
 

<script> import { items } from './store.js'; let newItem = ''; function addItem() { items.update(items => [...items, newItem]); newItem = ''; } </script>

Let's break down this code:

  • We import the items store from store.js.
  • We use the items.update() method to update the items store by adding the newItem to the end of the array.
  • We set the newItem variable to an empty string after adding the item to the list.
  1. Update List.svelte to use the items store:
  • Import the items store from store.js by adding the following code to the top of List.svelte:
 

import { items } from './store.js';

  • Replace the items prop with the items store in the script section:
 

<script> import { items } from './store.js'; let filteredItems = []; $: filteredItems = $items.filter(item => item.toLowerCase().includes($searchQuery.toLowerCase()) ); export let searchQuery; </script>

Let's break down this code:

  • We import the items store from store.js.
  • We use the $items variable to access the value of the items store.
  • We use a $: reactive statement to update the filteredItems array whenever the value of $items or $searchQuery changes.
  • We export the searchQuery prop so that it can be passed down from the App component.
  1. Update App.svelte to pass the searchQuery prop to List:
  • Add the searchQuery variable to the App component:
 

<script> import List from './List.svelte'; import { items } from './store.js'; let newItem = ''; let searchQuery = ''; function addItem() { items.update(items => [...items, newItem]); newItem = ''; } </script>

  • Pass the searchQuery prop to the List component:
 

<List {searchQuery} />

  1. Test the web application: In your browser, you should see the same web application as before, but now the list of items

y the items Svelte Store. Try adding some items to the list, and then use the search bar to filter the list.

You can see that the Svelte Store makes it easy to share state between components and keep the state consistent across the entire application. With the Svelte Store, we don't need to pass props up and down the component tree, or rely on events to update the state. Instead, we can simply update the store, and any components that are subscribed to the store will be updated automatically.

Conclusion

Svelte.js is a modern web framework that offers many benefits over traditional frameworks like React and Vue. With its reactive and component-based architecture, Svelte makes it easy to build fast, responsive, and scalable web applications. In this article, we covered the basics of Svelte.js, including components, props, events, and the Svelte Store. We also built a simple web application to demonstrate these concepts in action.

While this article only scratches the surface of what Svelte.js can do, we hope that it provides a solid foundation for you to explore this exciting new web framework. Whether you're building a simple single-page application or a complex web application, Svelte.js can help you build faster, more efficient, and more maintainable web applications. 

Our Svelte.js training course is the perfect way to get started. 

Here are some links to official documentation for Svelte.js:

  1. Svelte.js website: https://svelte.dev/
  2. Svelte.js tutorial: https://svelte.dev/tutorial/
  3. Svelte.js API reference: https://svelte.dev/docs
  4. Svelte.js REPL (Read-Eval-Print Loop): https://svelte.dev/repl/
  5. Svelte.js GitHub repository: https://github.com/sveltejs/svelte

These resources provide comprehensive documentation on various aspects of Svelte.js, including the language syntax, lifecycle methods, component API, store API, and more. They also include examples and demos to help you get started with Svelte.js quickly and easily.

 

 

About the author: Daniel West
Tech Blogger & Researcher for JBI Training

CONTACT
+44 (0)20 8446 7555

[email protected]

SHARE

 

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

POPULAR

Rust training course                                                                          React training course

Threat modelling training course   Python for data analysts training course

Power BI training course                                   Machine Learning training course

Spring Boot Microservices training course              Terraform training course

Kubernetes training course                                                            C++ training course

Power Automate training course                               Clean Code training course