blog ✏️ | about 👨🏻‍💻 | work 🏋️‍♀️ |

Hello Svelte 👋

Welcome to my site! In this guide, we’ll embark on an exciting journey to explore the world of Svelte and equip you with the tools to build fast and interactive web applications.

Svelte - I highly recommend checking it out - the interactive tutorial is perfect to get your feet wet, with no setup whatsoever.

What is Svelte?

Svelte is not just another JavaScript framework; it’s an entirely new approach to building user interfaces. Unlike traditional frameworks that do a lot of work in the browser, Svelte shifts much of the work to build time, resulting in leaner and faster code during runtime. This means your applications load faster and provide a smoother user experience.

Why Choose Svelte?

  1. Ease of Learning: Svelte’s clean and intuitive syntax makes it an excellent choice for both beginners and experienced developers.

  2. Performance: Svelte’s compilation approach significantly optimizes the code, leading to faster loading times and smoother animations.

  3. Responsiveness: Svelte’s reactivity system allows you to create dynamic interfaces with minimal effort.

  4. No Virtual DOM: Unlike other frameworks, Svelte doesn’t rely on a virtual DOM, potentially leading to even better performance.

Setting Up Your First Svelte Project

Let’s start by creating your first Svelte project. Follow these steps:

  1. Install Node.js: Make sure Node.js is installed on your computer.

  2. Install Svelte: Open your terminal and run the following command to install the latest Svelte project template:

npm create svelte@latest my-app
  1. Navigate to the Project: Move to the project directory:
cd my-app
  1. Install Dependencies: Install project dependencies using npm:
npm install
  1. Start the Development Server: Run the development server and open your new Svelte app in a web browser (the server will run on port 5173):
npm run dev

Project Structure

Once your Svelte app is ready and running, there are two essential concepts:

  • Each page in your app is a Svelte component.
  • You create pages by adding files to the src/routes directory in your project.

A typical Svelte project structure looks like this:

my-project/
├ src/
│ ├ lib/
│ │ ├ server/
│ │ │ └ [your server library files]
│ │ └ [your library files]
│ ├ params/
│ │ └ [your parameter matches]
│ ├ routes/
│ │ └ [your routes]
│ ├ app.html
│ ├ error.html
│ ├ hooks.client.js
│ └ hooks.server.js
├ static/
│ └ [your static assets]
├ tests/
│ └ [your tests]
├ package.json
├ svelte.config.js
├ tsconfig.json
└ vite.config.js

You’ll also find common files like .gitignore and .npmrc (and potentially .prettierrc and .eslintrc.cjs, if you selected those options when running npm create svelte@latest).

The src Folder

The src folder contains the heart of your project. Everything except src/routes and src/app.html is optional.

  • The lib folder holds your library code (tools and components), which you can import using the alias $lib, or bundle using svelte-package.
    • The server subfolder contains only server-specific library code. It can be imported using the alias $lib/server, and Svelte prevents you from importing it in client-side code.
  • The params folder contains any parameter matches your app needs.
  • The routes folder contains your app’s routes. You can also encapsulate other components that are only used within a specific route here.
  • The app.html file is your page template—a HTML document containing the core elements.

Routing and Layout in SvelteKit

In the essence of SvelteKit lies the file-based routing. Your app’s routes—URL addresses that users can access—are defined by directories in your codebase:

Examples

  • The page route +page.svelte:
<!--- File: src/routes/+page.svelte --->
<h1>Welcome to My Site!</h1>
<a href="/about">About My Site</a>
  • Page route +page.svelte for the “About” page:
<!--- File: src/routes/about/+page.svelte --->
<h1>About This Site</h1>
<p>Comment: This space will be filled soon...</p>
<a href="/">Home</a>
  • Page route +page.svelte for a blog post:
<!--- File: src/routes/blog/[slug]/+page.svelte --->
<script>
	/** @type {import('./$types').PageData} */
	export let data;
</script>

<h1>{data.title}</h1>
<div>{@html data.content}</div>

Often, your page will need to load some data before it can render. To achieve this, you can add a +page.js module exporting a load function:

/// File: src/routes/blog/[slug]/+page.js
import { error } from '@sveltejs/kit';

/** @type {import('./$types').PageLoad} */
export function load({ params }) {
	if (params.slug === 'hello-world') {
		return {
			title: 'Hello, World!',
			content: "Welcome to Khalid Alshahil's blog..."
		};
	}

	throw error(404, 'Not Found');
}

+page.server.js Module: If a load function can only be run on the server—e.g., if it needs to fetch data from a database or access environment variables like API keys.

Layouts (+layout):

You can create a layout that applies to multiple pages using +layout.svelte. Customize the layout by adding different elements, styles, and behaviors. For example, a simple layout with a navigation bar:

/// File: src/routes/+layout.svelte
<nav>
	<a href="/">Home</a>
	<a href="/about">About</a>
	<a href="/settings">Settings</a>
</nav>

<slot></slot>

Error Page (+error):

When an error occurs during loading (load function), SvelteKit presents the default error page. You can customize this page using the +error.svelte file. For example:

<!--- File: src/routes/blog/[slug]/+error.svelte --->
<script>
	import { page } from '$app/stores';
</script>

<h1>{$page.status}: {$page.error.message}</h1>

Server Files (+server):

You can create API routes using +server.js files, which provide full control over responses. For instance, you can create a /api/random-number route using a GET handler:

/// File: src/routes/api

/random-number/+server.js
import { json } from '@sveltejs/kit';

/** @type {import('./$types').RequestHandler} */
export function GET({ url }) {
	const min = Number(url.searchParams.get('min') ?? '0');
	const max = Number(url.searchParams.get('max') ?? '1');
	const random = min + Math.random() * (max - min);

	return new Response(String(random));
}

Enjoy the Magic of Svelte

Congratulations, you’ve taken your first steps into the enchanting world of Svelte! This guide only scratches the surface of what Svelte can achieve. Explore the official documentation, experiment with components, and unleash your creativity.

Remember, Svelte empowers you to build exceptional web applications with less code and better performance. It’s time to unleash your potential in the world of web development with Svelte!

To continue your adventure with Svelte, visit the official Svelte documentation and explore the vibrant Svelte community.

If you want to learn more about Svelte, I highly recommend watching this talk by Rich Harris, the creator of Svelte.

Happy Svelting!