Introduction to SvelteKit

Daniel Boadzie
9 min readJan 18, 2023

--

Introduction to SvelteKit

In my previous article, we discussed 6 reasons why Svelte, particularly Sveltekit, is ideal for AI applications. As promised, in this subsequent article, we will delve deeper into these points and provide practical examples of how Sveltekit can be used for AI applications. In order to fully understand the capabilities of Sveltekit for AI, it is essential to have a solid understanding of the entire Sveltekit library. In this and upcoming articles, I will guide you through the basics of Sveltekit and show you how it can be used to build powerful AI applications.

What is SvelteKit?

SvelteKit is an application framework built on top of the Svelte JavaScript framework. It provides a set of tools and conventions for building web applications with Svelte, including a development server, a build system, and a set of libraries for common tasks such as routing, state management, and data fetching.

SvelteKit allows for building web applications that are fast, lightweight, and easy to maintain. It uses a component-based approach to building user interfaces, where each component represents a reusable piece of UI. The Svelte compiler then converts these components into efficient JavaScript code that runs in the browser.

SvelteKit also offers a set of features that makes it easy to develop and deploy web applications, such as server-side rendering, code splitting, and automatic routing.

Because SvelteKit compiles your components into efficient JavaScript code, it allows you to easily utilize well-known JavaScript APIs such as fetch for data fetching and manipulation. Instead of reinventing the wheel, SvelteKit utilizes APIs that are well-known and loved by developers. This not only allows for faster and more efficient web applications but also makes it easy to integrate with a wide range of existing JavaScript libraries and tools.

It also provides a developer experience that is modern, easy, and fun. SvelteKit uses the latest web technologies and best practices to help you build web applications that are fast, lightweight and easy to maintain.

SvelteKit 101

Getting started with SvelteKit requires having Node.js installed on your system. If you do not already have it, you can download it from the official website. Once you have Node.js installed, you can use the pnpm package manager to scaffold a new SvelteKit project. Pnpm is a great choice for a package manager as it not only is efficient in package installation but also allows for future storage and use of packages.

While prior experience with Svelte may be beneficial, it is not a requirement as we will provide explanations and examples of the syntax as we proceed.

Locate a directory where you would like to create your project and run the following command in your terminal:

pnpm create svelte@latest sveltekit_intro

If the process is successful, you will be presented with a prompt that will ask you to select the type of project and features you wish to include. In this example, we will choose the skeleton project option with support for Prettier and ESLint, and without TypeScript.

Once you have selected the options, you will need to install the dependencies for the project, which can be done by running the following command from the project’s directory:

# cd sveltekit_intro
pnpm install

Incorporating Tailwind CSS for styling

In addition, we can also install Tailwindcss, Daisyui and the Tailwindcss typography plugin to enhance the styling and design capabilities of our project, because why not. Fortunately, there is a useful tool called “svelte-add” that is specifically designed for this purpose.

npx svelte-add@latest tailwindcss --daisyui --typography

To install these new dependencies, you will need to use the following command:

pnpm install

Now open the project in your favorite editor, mine is Vscode.

Understanding the directory structure

│   └── vite -> .pnpm/vite@4.0.4/node_modules/vite
├── package.json
├── pnpm-lock.yaml
├── postcss.config.cjs
├── README.md
├── src
│ ├── app.html
│ ├── app.postcss
│ └── routes
│ ├── +layout.svelte
│ └── +page.svelte
├── static
│ └── favicon.png
├── svelte.config.js
├── tailwind.config.cjs
└── vite.config.js

The root directory contains the following files and directories:

  • vite is a symlink to the Vite package installed by pnpm.
  • package.json contains information about the project and its dependencies.
  • pnpm-lock.yaml contains information about the specific versions of packages that were installed.
  • postcss.config.cjs contains configuration for PostCSS.
  • README.md contains a basic documentation for the project
  • src contains the source code of the application, including the root component and the routing configuration.
  • static directory contains the static assets like images, fonts and etc
  • svelte.config.js contains configuration for the Svelte compiler.
  • tailwind.config.cjs contains configuration for the Tailwind CSS.
  • vite.config.js contains configuration for the development server. The subdirectories of src contain the different components of the application, separated by functionality.

The src directory in a SvelteKit project contains the source code for the application. It contains the following items:

  • app.html: This is the root HTML template for the application.
  • app.postcss: This is the root PostCSS stylesheet for the application.
  • routes: This directory contains the routing configuration for the application. It contains the following items:
  • +layout.svelte: This is the layout component for the application. It defines the structure and common elements of the application, such as headers and footers.
  • +page.svelte: This is a template for the home page in the application. It defines the structure of the index page and includes the layout component.
  • other routes file can be added here as well.

These files and directories make up the basic structure of a SvelteKit application, and can be further expanded and customized to fit the needs of the project.

At this point, you should be able to see the default “Hello World” message when you run the application. To make changes to the application, you can edit the +page.svelte file. Once you have made your changes, you can re-run the application to see the updated results.

pnpm dev

Now visit http://localhost:5173/ in your browser.

And just like that, we have created our first SvelteKit application! How cool. To test the functionality and flexibility of the application, you can try making changes to the +page.svelte file and saving it. You will see that the application will hot-reload instantly, thanks to the power of Vite.

Creating and handling routes

Routing is a crucial aspect of any web application, and Sveltekit makes it easy to handle. SvelteKit uses a file-system based router, which means that you can create a new folder(say about) in the src/routes/ directory and include a +page.svelte file inside it, and you have a new route to /about. Isn't that cool? This approach provides a simple and intuitive way to handle routing and makes it easy to add new routes to your application.

Additionally, the folder can also contain a +layout.svelte file to define the layout of the content specifically for that route and many other files we will see later.

about page

What if we want to link to the the about page instead of manually typing it in the address bar? With Sveltekit, that is easy all we need is to add an a tag with an href to /about. In SvelteKit, there is no need to use any specialized Link component to navigate to other pages. Awesome right?

<!--- src/routes/+page.svelte -->
<a class="underline text-blue-500" href="/about">About page</a>

Integration an API

So far out application is minimal and boring. It is about time we spice it by introducing you to another another cool feature of Sveltekit: loading data. To demonstrate this feature, we will use the popular JSON Placeholder API as a source of free, fake data for testing and prototyping purposes.

Let’s create a new +page.js file in the src/routes folder. This file will be used to retrieve data from the API. The file should look similar to the following:

// src/routes/+page.js
export async function load() {
const res = await fetch('https://jsonplaceholder.typicode.com/todos');
const posts = res.json();
return {
posts
};
}

This file exports a load function which utilizes the JavaScript fetch API to retrieve data from the JSON Placeholder API. The function uses the fetch API to make a GET request to the API endpoint, and then uses the await keyword to wait for the promise to resolve. The response from the API is then converted to a JSON and it is passed to the Svelte component as a special data prop.

We can now display the data in the +page.svelte component like this:

<!--- src/routes/+page.svelte -->
<script>
// import {page} from "$app/stores"
export let data;
</script>
<div class="grid lg:grid-cols-3 gap-4 ">
{#each data.posts as post }
<div class="rounded-sm bg-slate-50 p-5">
<a class="text-blue-400 text-xl font-bold" href="/{post.id}">{post.title}</a>
<p class="text-md text-slate-500">{post.body}</p>
</div>
{/each}
</div>

Notice that in Svelte, we use the convenient {#each objects as object }{/each} syntax to iterate over an array. We also added an a tag with a link to view an individual post. However, this page does not exist yet, so let's create it next. In the Svelte component, we are also receiving the data in a <script> tag with export let data as a prop.

To accomplish this, we need to create a new folder named [id] in the src/routes directory and place a +page.js file inside it. This file will be used to load the specific post identified by the id, hence the name of the folder. If we were using a slug as the parameter, the folder would be named [slug] instead.

// src/routes/[id]/+page.js
export async function load({ params }) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${params.id}/`);
const post = res.json();
return {
post
};
}

Then, we add the +page.svelte component to the [id] folder (parameterized folder).

<!--- src/routes/[id]/+page.svelte -->
<script>
export let data;
</script>

<section class="container mx-auto px-4 py-14">
<div class="m-auto w-1/2">
<h3 class="text-blue-400 text-4xl font-bold">{data.post.title}</h3>
<p class="text-md text-slate-500 my-4">{data.post.body}</p>
</div>
</section>

Note that even though we are placing the [id] folder within the routes folder, it could also be placed in a posts folder, for example.

Now, run your application and visit the root page, you will see something like this:

And when you click on a title, you will be taken to the page for that particular post:

single post page

You will notice that this is lightning fast. This is happening because the page is preloaded when you hover over it, thanks to this line in the app.html file:

<!-- src/app.html -->
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>

Adding a Navbar

Let complete our app by adding a navbar to the +layout.svelte file.

<!--- src/routes/+layout.svelte --->
<script>
import '../app.postcss';
</script>

<nav class="p-4 text-white bg-slate-700 display flex items-center justify-start gap-4">
<a class="font-bold text-lg hover:text-blue-500" href="/">SvelteKit Intro Blog</a>
<a class="font-bold text-lg hover:text-blue-500" href="/about">About page</a>
</nav>

<main>
<slot />
</main>

The <slot/> section is where our page components will be injected. The app should now look like this:

final app

Conclusion

In conclusion, SvelteKit is a powerful and easy to use framework that makes building web applications a breeze. With its file-system based routing, you can easily create new pages and routes without the need for any additional link components. The use of the fetch API and the ability to preload pages makes it a great choice for building fast and responsive web apps. The examples we have covered in this article are just the beginning of what can be achieved with SvelteKit. With its simplicity and ease of use, SvelteKit is definitely worth checking out for your next web project. In the next article, we will dive deeper into the capabilities of this powerful framework and explore more advanced features of SvelteKit.

The code for this article can be found here

--

--

Daniel Boadzie
Daniel Boadzie

Written by Daniel Boadzie

Data scientist | AI Engineer |Software Engineering|Trainer|Svelte Entusiast. Find out more about my me here https://www.linkedin.com/in/boadzie/

No responses yet