Birch.dev
Back

Sveltekit

Published: 2023-07-02

Getting started

Create a new project Make sure node 18+ is installed.

npm create svelte@latest

At the prompt select:

  • Skeleton project
  • Typescript syntax
  • We can then select the option to install Eslint, Prettier, Playwrite and Vite.

Install the dependancies:

npm i

To run the application

npm run dev

Application Structure

vite.config.ts contains the build configuration svelte.config.ts contains the svelte configuration, this can be extended to deploy to numerous different environments. static contains all the static assets for the project such as images, fonts and other assets. src containst the source

The start page of the project is app.html

In the src folder create a lib folder, this will be accesible using the shorthand $lib through the application. We can place components and utilities in the folder and have a shorthand way to reference them.

Extensions

Install the Svelte for VS Code extension. This has the ability to generate boiler plate pages, right click on a folder to access it though the context menu or bring up the command pallete and type sveltekit

## Routes

Sveltekit uses folder based routing, the url is determined by the folder structure.

Folders can be be:

  • static - hello would route to www.mysite.com/hello
  • dynamic - [username] svelte sees the variable username as a route parameter. We could use the code params.username = 'Bob' and Svelte would have the url route to www.mysite.com/bob

Page Types

There are 4 types of files in svelte and each of these files can end with .svelte, .server.ts and .ts.

By default the first page load is rendered on the server, any navigation or updates after that will be handled by the client.

Page

The building blocks of svelte

+page.svelte

  • Used for: building UI
  • Runs on: client & server

+page.ts

  • Used for: data fetching
  • Runs on: client & server

+page.server.ts

  • Used for: data fetching
  • Runs on: server ONLY

Layout

UI can be shared across child routes

+layout.svelte

  • Used for: building UI
  • Runs on: client & server

+layout.ts

  • Used for: data fetching
  • Runs on: client & server

+layout.server.ts

  • Used for: data fetching
  • Runs on: server ONLY

Server

+server.ts

  • Used for: API routes
  • Runs on: server ONLY

Error

Error message for a page when data fetching fails

+error.svelte

  • Used for: API routes
  • Runs on: server ONLY
This is content