There are two underlying concepts of SvelteKit:
- Each page of your app is a Svelte component.
- Pages are created by adding files to the
src/routesdirectory of your project. Pages are server-rendered so a user's first visit is as fast as possible. A client-side app then takes over.
Create a directory called
src/routes. Inside the directory create an
mkdir src/routes/about touch src/routes/about/index.svelte
<svelte:head> element allows you to insert elements inside the
<head> of your document. Create a
title with the
<svelte:head> tag. After that include an
<h1> header tag and a
<p> paragraph tag.
<svelte:head> <title>About</title> </svelte:head> <h1>About</h1> <p>This pages tells you about stuff!</p>
We don't have a link yet to navigate to the page, but we do already have our route created. Enter
http://localhost:3000/about to see the next page.
To create links between the pages we'll use
<slot /> tag indicates where a component places its children, so our layout component is the parent of our pages.
<main> <nav> <a href="/"> home </a> <a href="/about"> about </a> </nav> </main> <main> <slot /> </main>
What if we wanted to extract the navigation bar into its own component? First we'll create a file called
Take the code contained inside
$layout.svelte and move it to
<nav> <a href="/" > home </a> <a href="/about" > about </a> </nav>
$layout.svelte include an
Nav inside a
<script> tag. Then include
<Nav /> inside the
<script> import Nav from '$lib/Nav.svelte'; </script> <main> <Nav /> </main> <main> <slot /> </main>
Your project should look and function exactly the same after this change.