How to Build Your First Svelte App: A Step-by-Step Tutorial

Building your first Svelte app can be an exciting experience. Svelte is a modern JavaScript framework that compiles your code into highly efficient vanilla JavaScript. This tutorial will guide you through the process step by step, from setting up your environment to deploying your app.

Prerequisites

  • Basic knowledge of HTML, CSS, and JavaScript
  • Node.js and npm installed on your computer
  • A code editor such as Visual Studio Code

Setting Up Your Development Environment

First, verify that Node.js and npm are installed by running the following commands in your terminal:

node -v and npm -v

If they are not installed, download and install Node.js from the official website.

Creating a New Svelte Project

Use the Svelte template to create a new project. Run the following command:

npx degit sveltejs/template my-svelte-app

Navigate into your project directory:

cd my-svelte-app

Install the dependencies:

npm install

Running Your Svelte App

Start the development server with:

npm run dev

Open your browser and go to http://localhost:5173. You should see the default Svelte app running.

Understanding the Project Structure

The main files and folders include:

  • src/App.svelte: The main component of your app.
  • public/index.html: The HTML template.
  • package.json: Project dependencies and scripts.

Editing Your First Svelte Component

Open src/App.svelte in your editor. You will see some default code:

Example:

<script> ... </script>

<style> ... </style>

<h1>Hello world!</h1>

Modify the content to display your own message or add new components.

Adding New Components

Create a new file in the src folder, for example MyComponent.svelte. Add your component code:

Example:

<script> ... </script>

<div>This is my custom component!</div>

Import and use this component in App.svelte:

import MyComponent from './MyComponent.svelte';

<MyComponent />

Building and Deploying Your App

When ready to deploy, build your app with:

npm run build

This creates a build folder with optimized files. You can host these files on any static site hosting service.

Conclusion

Congratulations! You have successfully created your first Svelte app. Continue exploring its features, components, and styling options to build more complex applications. Happy coding!