Home Web Development SvelteKit Up and Running

SvelteKit Up and Running

By Dylan Hildenbrand
books-svg-icon Book
eBook $27.99
Print $34.99
Subscription $15.99
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $27.99
Print $34.99
Subscription $15.99
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Initial Setup and Project Structure
About this book
The JavaScript ecosystem has grown vast, complex, and daunting for newcomers. Fortunately, SvelteKit has emerged, simplifying the process of building JavaScript-based web applications. This book aims to demystify SvelteKit, making it as approachable as it makes web app development. With SvelteKit Up and Running you’ll be introduced to the philosophy and technologies underlying SvelteKit. First, you’ll follow a standard educational programming approach, progressing to a 'Hello World' application. Next, you’ll explore the fundamental routing techniques, data loading management, and user submission, all through real-world scenarios commonly encountered in day-to-day development, before discovering various adapters employed by SvelteKit to seamlessly integrate with diverse environments. You’ll also delve into advanced concepts like dynamic route management, error handling, and leveraging SvelteKit to optimize SEO and accessibility. By the end of this book, you’ll have mastered SvelteKit and will be well-equipped to navigate the complexities of web app development.
Publication date:
July 2023
Publisher
Packt
Pages
166
ISBN
9781804615485

 

Initial Setup and Project Structure

I’ve been developing web applications for almost a decade now and the landscape has changed drastically since I began. To put that in reference, I’ve been building websites since JavaScript was so poorly supported by mainstream browsers that jQuery became the de facto standard for building interactive frontend experiences. But over time, we’ve seen more browsers willing to support ECMAScript standards and the ones that didn’t have died off (good riddance, Internet Explorer). JavaScript then re-emerged as a viable language. And with the rise of Node.js, developers could finally build an entire application, both frontend and backend, in a single programming language. JavaScript had taken over the web development world and firmly cemented its foothold.

As the technologies have matured, so too have development experiences. With the arrival of SvelteKit 1.0, we developers are given an intuitive experience allowing us to couple frontend and backend logic together in a way that leaves us wondering, “How did we do this before?” Before we dive into that experience, we’ll need to cover a few things.

Firstly, we’ll cover the prerequisites for developing applications with SvelteKit. We’ll then move on to how SvelteKit is installed and discuss how projects are typically structured. From there, we’ll build a “Hello, World!” application so we can see everything in action.

To summarize, we’ll discuss these topics in this chapter:

  • Prerequisites
  • Installing SvelteKit
  • SvelteKit’s Project Structure
  • Hello, World!”

After covering all of this material, you should be reasonably comfortable setting up a new SvelteKit application for your next project.

 

Technical requirements

The complete code for this chapter is available on GitHub at: https://github.com/PacktPublishing/SvelteKit-Up-and-Running/tree/main/chapters/chapter01

 

Prerequisites

To get the most out of this book and ensure you retain the information provided, it is recommended to work alongside the material as you read it. Type the commands and code shown into your project, but also feel free to experiment. To do this effectively, you will need a computer running Windows, macOS, or a Linux-based operating system as well as access to a terminal or command-line interface. Most modern computer hardware capable of running the latest versions of the aforementioned operating systems should be sufficient for your needs. Specifically, you’ll need a system with a minimum of 1 GB of RAM and at least a 1.6 GHz processor. This should work just fine for developing with SvelteKit, though performance may vary for your operating system.

Like many other web development projects, you’ll also need a web browser. The latest version of Firefox, Chrome, or Safari is recommended. You will also need to install Node.js. It is recommended to use the latest Long-Term Support (LTS) version, which, at the time of writing this book, is version 18. An alternative and often easier method of managing Node.js installation is the Node Version Manager (NVM) project. It allows users to easily install and change versions of Node.js. See the end of this chapter for resources related to both Node.js and NVM. Alongside that, you will also need a package manager. This book will utilize npm as it is available with a standard Node.js installation. It is possible to use yarn in place of npm, but it is probably easier to just use npm. If you’re worried about performance, pnpm will also work.

The final tool required will be a text editor or Integrated Development Environment (IDE). The Svelte community supports many editors, but the official SvelteKit documentation recommends using Visual Studio Code (VS Code) along with the Svelte extension. While it is not required, it can certainly ease the pain of dealing with the different syntaxes found in Svelte components. To install Svelte for VS Code, launch VS Code Quick Open with Ctrl + P, type ext install svelte.svelte-vscode, and hit Enter.

In summary, you will need the following:

  • A macOS, Windows, or Linux-based computer
  • A modern web browser (Firefox, Chrome, or Safari)
  • Terminal access
  • Node.js 18+ LTS
  • A package manager (npm comes installed with Node.js)
  • A text editor/IDE (with the recommended Svelte extension)
 

Installing SvelteKit

To begin, open your terminal or command-line interface and navigate to a directory where you are comfortable starting a new project. From there, we’ll run three simple commands. The first will create a new SvelteKit project with various prompts to initialize the application, the second will install dependencies, and the third will start our development server:

npm create svelte@latest
npm install
npm run dev

When running the first command, you’ll be presented with several prompts. The first of these will ask you to install create@svelte to which your response should be y for yes. When prompted to select a directory to install the project in, leave the option blank to use the current directory (or specify the directory if you’d prefer to). You’ll then be asked which template to use. We’ll be working primarily with the option Skeleton project but feel free to come back and give the SvelteKit demo app a try in another directory at your convenience.

The next prompt pertains to TypeScript (TS) usage, for which SvelteKit has excellent support. However, to keep the focus of this book on SvelteKit itself and to appeal to developers that may not yet be familiar with TS, we will be using plain JavaScript. As such, to properly follow along with this text, you should select No. If you feel comfortable enough with TS, then by all means, select Yes. Be sure to select Yes for ESLint and Prettier support as they will very likely save you headaches and further improve your development experience. It is also recommended to include supported testing packages, but this book will not be covering testing strategies.

After installing the project dependencies with npm install, we run npm run dev, which starts our development server. The output from the command should look similar to that shown in Figure 1.1.

Figure 1.1 – Showing the output from the Vite development server

Figure 1.1 – Showing the output from the Vite development server

Notice how quickly Vite starts our development server. Even though this is a bare-bones application, other bundling tools would have taken multiple seconds whereas Vite was ready in under one second. As shown in the output displayed in the terminal, the site can be viewed by navigating to http://localhost:5173/ in your browser. If you would like to access the site from a device other than your development machine, for instance, on a mobile device, then you may append –-host to the appropriate npm script found in the package.json project file. Under the scripts entry, the new command would look like "dev": "vite dev –-host".

We’ve just covered the installation process for SvelteKit. At this point, it should be trivial for you to install your own SvelteKit-based project. We’ve covered how the various prompts from the create@svelte package allow you to customize the project to your liking. Now, let’s take a look at how a typical SvelteKit project is structured.

 

SvelteKit’s Project Structure

Once you have installed a new SvelteKit project, open the project directory in your preferred editor. Within that folder, you’ll notice files that are commonly found in the root project folder of JavaScript applications such as package.json, .gitignore, and README.md, as well as configuration files pertaining to SvelteKit (svelte.config.js) and Vite (vite.config.js). You’ll also notice three subfolders: static/, tests/, and src/. Let’s look at them in detail in the following sections.

static/

This folder is where you may place static assets such as robots.txt (your guidelines for search engine site crawlers), static images such as favicons, or even a global CSS style sheet. These files should be able to be served “as is.” Files located in this folder will be available to your application logic as if they existed in the root folder of your project, that is, /robots.txt. You can also access them by prefixing the file path with %sveltekit.assets%. Note that if files here are changed, you may need to manually refresh the page to see changes. In some cases, you may even need to restart your development server as Vite has strong opinions about caching. You should not attempt to access files included in this directory programmatically. Rather, the paths should be “hardcoded” wherever the assets here are included.

tests/

Logically, tests from the Playwright package (included in the various prompts we said yes to) are located here. To run the Playwright browser test, use the npm script npm run test. Unit tests from Vitest will be included alongside your source code. For example, if you included a file called utilities.js, unit tests for it would live alongside it as utilities.test.js. Vitest is a package from the developers of Vite that enables simple testing for Vite-based applications. Test-Driven Development (TDD) is an excellent practice to follow to ensure code performs as it is expected to. However, it is beyond the scope of this book.

src/

You will be spending most of your time working in this folder as this is where the core logic for a SvelteKit application lives. There are a few files and directories that should be taken note of at this time:

  • routes/
  • lib/
  • app.html

routes/

The first subfolder to take note of is src/routes/. This directory will contain most files necessary for managing SvelteKit’s file-based routing mechanism. Its sibling folder src/params/ will be covered later on, but for now, assume most logic related to managing the routes of your application is located here. As a brief example, if you’d like to add a static “about” page, then you would do so by creating src/routes/about/+page.svelte containing the appropriate markup and text.

lib/

Svelte components and various other utilities can be placed in the src/lib/ subfolder. This folder may not be present in the skeleton project template so you’ll have to add it on your own. It will be shown in the SvelteKit demo app. By placing your components here, you can easily reference them in import statements later on as the $lib/ alias will be available throughout the application.

app.html

There are more files to cover that we will address later on, but for now, the final mention is app.html. This file serves as the base for the rest of your application to build off of. When opened, you’ll notice it contains references to %sveltekit.head%, which SvelteKit uses for injecting various script and link tags, and %sveltekit.body%, which is used for injecting the markup generated for the application.

To recap, the static/ directory contains files that don’t frequently change, tests/ contains tests from the Playwright package, and src/ contains the source code of your project. Most Svelte components and other utilities you create can be placed at src/lib/ so as to be easily accessed via the $lib/ alias in import statements. If you’d like to add a new route to your application URL, you can do so by creating a +page.svelte file inside a directory with the corresponding name at src/routes/. And finally, your application will need a base to build off. That’s where app.html comes in. I’m sure you’re eager to finally build something, so let’s do it.

 

Hello World Application

Now that we know a bit about what we’re looking at in a freshly initialized SvelteKit project, it seems appropriate to build a “Hello, World!” application. We’ll begin by opening src/routes/+page.svelte in our editor. At this point, it should only contain basic HTML code:

<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>

Since this file lives directly inside the src/routes/ directory and not a sub-directory, it is available in the browser as the URL's root route (i.e., /). If we were to create a new folder within the routes directory (i.e., src/routes/hello/) and place another +page.svelte file inside of that (i.e., src/routes/hello/+page.svelte), then we would make the /hello route available as a valid URL for our app. We’ll cover more advanced routing techniques in later chapters, but for now, just know that to add a new route, you’ll need to create a folder using the desired route name in the routes directory as well as a +page.svelte file.

Svelte Components

Readers familiar with Svelte will have noticed that the +page.svelte file extension is that of a Svelte component. That’s because it is a Svelte component! As such, we can adjust the HTML in it, customize the look with CSS in <style> tags, write JS inside of <script> tags, and import other Svelte components. If you’re unfamiliar with Svelte components, it’s recommended to learn at least the basics before continuing further. Check out Svelte 3 Up and Running by Allessandro Segala or visit the official Svelte website (https://svelte.dev) for more information.

Let’s make some changes to src/routes/+page.svelte to see what’s happening. Change the inner text of the <h1> tag to read Hello, World!, like so:

<h1>Hello, World!</h1>

Thanks to Vite, the page in our browser is updated immediately after saving. If your setup has dual monitors available with code shown on one and your browser on the other, you’ll quickly see how valuable Hot Module Replacement (HMR) can be. The change we’ve made is all well and good, but it isn’t really a “Hello, World!” application if users can’t change the text. For a true “Hello, World!” example, we need to show some text that has been provided by the user. The following code is an implementation showing just that:

<script>
  let name = 'World';
</script>
<form>
  <label for="name" >What is your name?</label>
  <input type="text" name="name" id="name" bind:value={name} />
</form>
<h1>Hello, {name}!</h1>

This simple Svelte component creates a variable named name with the default value of “World.” From there, the HTML gives us a basic form binding the text input value to our variable and outputting the text inside an HTML <h1> tag. Thanks to Svelte’s reactivity and the binding of the text input value to the name variable, the text provided is shown immediately, even as it is typed.

Figure 1.2 – The output from our “Hello, World!” component

Figure 1.2 – The output from our “Hello, World!” component

 

Summary

In this chapter, we discussed some of the prerequisite knowledge and tools needed for getting started with SvelteKit. You likely already had a computer running a capable operating system with a browser installed. You may even have had the latest LTS version of Node.js installed with the npm package manager. We also briefly touched on getting your editor prepared by installing Svelte-specific extensions.

We continued by covering the installation process of SvelteKit. The prompts provided during the installation make setting up a new SvelteKit project simple and easily customized to a developer’s liking.

After the project installation, we took a high-level look at SvelteKit’s project structure. While the tests/ and static/ directories are fairly straightforward, some nuances lie within the src/ folder. For instance, keeping various Svelte components and other utilities in the src/lib/ folder can help keep a project from becoming difficult to navigate. Components located there are also easily accessed across application code via the $lib/ alias.

We also created a rudimentary “Hello, World!” application. It showcased how simple SvelteKit makes it to start building an application from scratch.

In the next chapter, we’ll go over some of the various configuration options you may need to tweak in both SvelteKit and Vite to customize them to suit your needs.

 
About the Author
  • Dylan Hildenbrand

    Dylan Hildenbrand is a full-stack web developer with a penchant for understanding how things work. Over the past decade, that desire to know “how things work” has led Dylan to a robust skillset ranging from front and back-end development to database administration, Linux server administration, and automation of application deployments and testing procedures. Dylan graduated from Minot State University in 2012 with a degree in Computer Science. When not proselytizing to strangers about switching to Linux or Vim, Dylan enjoys administering and automating his “homelab,” playing video games, playing board games with his wife, wrestling with his two children, and writing about web development on his website; closingtags.com.

    Browse publications by this author
SvelteKit Up and Running
Unlock this book and the full library FREE for 7 days
Start now