DEV Community

Cover image for Svelte.js Tutorial
kiraaziz
kiraaziz

Posted on

Svelte.js Tutorial

Introduction to Svelte.js

Svelte.js is a modern JavaScript framework that allows you to build web applications by writing components. It focuses on efficient rendering and minimal bundle sizes, resulting in fast and optimized applications. In this tutorial, we'll cover the basics of Svelte.js and explore various examples.

Table of Contents

  1. Installation and Setup
  2. Creating Your First Svelte Component
  3. Reactive Declarations and Binding
  4. Handling User Input
  5. Conditionals and Loops
  6. Component Lifecycle
  7. State Management
  8. API Integration
  9. Building and Deployment

1. Installation and Setup

To get started with Svelte.js, you need to have Node.js installed on your machine. Once you have Node.js, follow these steps:

  1. Open a terminal or command prompt.
  2. Create a new directory for your Svelte project: mkdir svelte-tutorial
  3. Navigate into the project directory: cd svelte-tutorial
  4. Initialize a new Node.js project: npm init -y
  5. Install Svelte.js as a dev dependency: npm install svelte --save-dev

2. Creating Your First Svelte Component

Let's create a simple "Hello World" component to get started. Create a new file called Hello.svelte in the project directory and add the following code:

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

<h1>Hello {name}!</h1>
Enter fullscreen mode Exit fullscreen mode

To render this component, create a new file called main.js and add the following code:

import Hello from './Hello.svelte';

const app = new Hello({
  target: document.body,
});
Enter fullscreen mode Exit fullscreen mode

Now, open the index.html file in your browser, and you should see "Hello Svelte!" displayed on the page.

3. Reactive Declarations and Binding

Svelte provides reactive declarations to update the UI automatically when the underlying data changes. Let's modify our Hello.svelte component to make the name changeable:

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

<input bind:value={name} placeholder="Enter your name" />

<h1>Hello {name}!</h1>
Enter fullscreen mode Exit fullscreen mode

Now, when you type in the input field, the name in the heading will update accordingly.

4. Handling User Input

In addition to reactive bindings, Svelte allows you to handle user input with event listeners. Let's add a button to greet the user:

<script>
  let name = 'Svelte';

  function greet() {
    alert(`Hello, ${name}!`);
  }
</script>

<input bind:value={name} placeholder="Enter your name" />
<button on:click={greet}>Greet</button>
Enter fullscreen mode Exit fullscreen mode

Clicking the "Greet" button will display a greeting message with the entered name.

5. Conditionals and Loops

Svelte supports conditional rendering and looping over data. Let's create a list component that displays a list of names:

<script>
  let names = ['Alice', 'Bob', 'Charlie'];
</script>

<ul>
  {#each names as name}
    <li>{name}</li>
  {/each}
</ul>

<button on:click={() => names = names.concat('Dave')}>Add Name</button>
Enter fullscreen mode Exit fullscreen mode

The list will initially display "Alice," "Bob," and "Charlie." Clicking the "Add Name" button will add a new name to the list.

6.

Component Lifecycle
Svelte components have lifecycle hooks that allow you to perform actions at specific stages of the component's lifecycle. Here's an example:

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

  onMount(() => {
    console.log('Component mounted');
  });

  onDestroy(() => {
    console.log('Component destroyed');
  });
</script>

<h1>Component Lifecycle Example</h1>
Enter fullscreen mode Exit fullscreen mode

Open the browser's developer console, and you'll see the "Component mounted" message when the component is rendered and the "Component destroyed" message when it's removed from the DOM.

7. State Management

Svelte makes state management straightforward with its built-in stores. Let's create a counter component that increments a counter value:

<script>
  import { writable } from 'svelte/store';

  let count = writable(0);

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

<h1>Counter: {$count}</h1>
<button on:click={increment}>Increment</button>
Enter fullscreen mode Exit fullscreen mode

The counter will update dynamically whenever the increment button is clicked.

8. API Integration

Svelte can easily integrate with APIs to fetch and display data. Here's an example using the fetch function:

<script>
  let user;

  async function fetchUser() {
    const response = await fetch('https://api.example.com/user');
    user = await response.json();
  }

  fetchUser();
</script>

{#if user}
  <h1>Welcome, {user.name}!</h1>
{else}
  <p>Loading...</p>
{/if}
Enter fullscreen mode Exit fullscreen mode

When the component is rendered, it will fetch the user data from an API and display a welcome message once the data is available.

9. Building and Deployment

To build your Svelte application for production, run the following command in your project directory:

npx svelte-kit build
Enter fullscreen mode Exit fullscreen mode

This will generate a build directory containing the optimized and bundled version of your application. You can then deploy the contents of the build directory to your hosting provider.

Congratulations! You've completed the Svelte.js tutorial. This should give you a solid foundation to build web applications with Svelte.js. Remember to explore the official documentation for more in-depth knowledge and advanced features.

Happy coding!

Top comments (2)

Collapse
 
miguel_siqueirareis profile image
Miguel Siqueira Reis

its like a vue js without template?

Collapse
 
kiraaziz profile image
kiraaziz

No it's much easier