Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
SvelteKit Up and Running
SvelteKit Up and Running

SvelteKit Up and Running: Leverage the power of a next-generation web framework to build high-performance web apps with ease

eBook
$18.99 $27.99
Paperback
$34.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Table of content icon View table of contents Preview book icon Preview Book

SvelteKit Up and Running

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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Develop JavaScript applications with an intuitive and beginner-friendly framework
  • Grasp the core concepts of SvelteKit effortlessly with real-world examples
  • Discover how SvelteKit minimizes obstacles in building modern web applications, enhancing productivity and efficiency

Description

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.

Who is this book for?

This book is for web developers aiming to enhance their SvelteKit skills. Whether you're selecting your first JavaScript framework or seeking to stand out among job applicants by adding the latest technology to your resume, this book is your ultimate guide to becoming a SvelteKit master. A solid understanding of HTML, CSS, JavaScript, and Svelte is a must.

What you will learn

  • Gain a comprehensive understanding of the core technologies of SvelteKit
  • Dive deep into SvelteKit's file-based routing system and uncover basic and advanced concepts
  • Master code organization in SvelteKit through effective data-loading techniques
  • Elevate your application's visibility by incorporating SEO and accessibility
  • Streamline the deployment process of your SvelteKit apps by using adapters
  • Optimize your SvelteKit app by exploring various configuration and tooling options

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 28, 2023
Length: 166 pages
Edition : 1st
Language : English
ISBN-13 : 9781804619650
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning

Product Details

Publication date : Jul 28, 2023
Length: 166 pages
Edition : 1st
Language : English
ISBN-13 : 9781804619650
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 101.96 109.97 8.01 saved
Real-World Svelte
$31.98 $39.99
Svelte with Test-Driven Development
$34.99
SvelteKit Up and Running
$34.99
Total $ 101.96 109.97 8.01 saved Stars icon

Table of Contents

17 Chapters
Part 1 – Getting Started with SvelteKit Chevron down icon Chevron up icon
Chapter 1: Initial Setup and Project Structure Chevron down icon Chevron up icon
Chapter 2: Configurations and Options Chevron down icon Chevron up icon
Chapter 3: Compatibility with Existing Standards Chevron down icon Chevron up icon
Part 2 – Core Concepts Chevron down icon Chevron up icon
Chapter 4: Effective Routing Techniques Chevron down icon Chevron up icon
Chapter 5: Deep Dive into Data Loading Chevron down icon Chevron up icon
Chapter 6: Forms and Data Submission Chevron down icon Chevron up icon
Chapter 7: Advanced Routing Techniques Chevron down icon Chevron up icon
Part 3 – Supplemental Concepts Chevron down icon Chevron up icon
Chapter 8: Builds and Adapters Chevron down icon Chevron up icon
Chapter 9: Hooks and Error Handling Chevron down icon Chevron up icon
Chapter 10: Managing Static Assets Chevron down icon Chevron up icon
Chapter 11: Modules and Secrets Chevron down icon Chevron up icon
Chapter 12: Enhancing Accessibility and Optimizing SEO Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Most Recent
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(11 Ratings)
5 star 54.5%
4 star 27.3%
3 star 18.2%
2 star 0%
1 star 0%
Filter icon Filter
Most Recent

Filter reviews by




John C Jul 30, 2024
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
This is a nice,, simple guide to using SvelteKit.Unfortunately, there's only about a page of context - where does this technology fit, how does it compare with others, when to choose it or not. That's what I was hoping for.Instead it gives a nice clear guide to setting it up & using it: just what the online documentation will help you do.I like its companion book - on Svelte itself - much better!
Amazon Verified review Amazon
Tomáš Daněk Jul 20, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
Amazon Customer Sep 05, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've been a big fan of Svelte for years, using several meta-frameworks as they were released and improved. Now with a standard like SvelteKit, I wanted to dive in and this book was released at such an opportune time!I learned how to roll a couple of features like 404/fallback pages just as I needed them, and certainly felt like this got me "up and running" as the title says.
Amazon Verified review Amazon
Mike Sep 01, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Before diving into this book you should have good knowledge of Svelte and REPL. This book helps to fill in knowledge gaps that the docs for those don't really address - while also providing an experienced reference for good code practices. This isn't a book for beginners, but it is a valuable reference tool for those utilizing Svelte.
Amazon Verified review Amazon
Jason Louv Aug 14, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is an excellent and timely book. I pre-ordered it and got it as soon as it came out, and I'm happy I did. Yes, as others have pointed out, you should start with the official SvelteKit docs and REPL. But in practice, they're not enough. This book fills in a lot of the blanks and brings a lot of valuable tidbits to the table. Even if you've worked through the docs, seeing the same material presented in a different format with a different take on it and different details is phenomenally useful. Well done Dylan!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.