Preface

Hello, and welcome to SvelteKit Up and Running! This book aims to be an easy-to-read guide introducing you to the core concepts of the refreshingly simple JavaScript (JS) framework known as SvelteKit. It was written to highlight what I felt were the core concepts of the framework. Because the JS landscape changes so frequently, this text should not be considered an authority on SvelteKit. Rather, the intention behind this book is to provide a resource that I wish was available to me when I was learning this promising new framework. As I often find myself wanting to learn high-level concepts first and then move on to finer details, so this book will too. However, before we begin, we must cover a few high-level concepts.

What is SvelteKit?

SvelteKit is an all-in-one solution to develop web applications using Svelte components. If you’re familiar with React, then you’ve likely heard of Create React App. While both Svelte and React are useful to create reusable components built with JS, each is more useful when given a means of utilizing those components.

Out of the box, SvelteKit provides mechanisms to handle routing; server-side rendering (SSR) supports TypeScript and enriches the development experience with features such as Hot Module Replacement (HMR), which automatically refreshes the browser when changes are detected in an application. This feature, and many others, are made possible by the tight coupling of SvelteKit with Vite.

How does Vite simplify development?

SvelteKit, and features such as HMR, wouldn’t be possible without Vite, which itself wouldn’t be possible without Rollup and esbuild. Vite differentiates itself from other bundling tools by providing a lightning-fast development server that leverages native ECMAScript Module (ESM) availability in modern web browsers. Vite accomplishes this by breaking application code into two parts – dependencies and source code.

Dependencies

Vite can provide a fast development server by pre-bundling each dependency from a project into its own ES module with esbuild. Whether those dependencies are in CommonJS, Universal Module Definition (UMD), or ESM formats is irrelevant to Vite, as it will convert them all to ESM on the initial application build. Doing this means the browser only has to make a single HTTP request for each dependency instead of a request for each import statement. This can greatly improve the performance of the development server, especially considering how quickly requests can add up in dependency-heavy applications.

Source code

Unlike dependencies, source code changes often during development. To keep the developers (you) of this source code happy, Vite utilizes a couple of clever approaches. Because modern browsers support native ES modules, Vite can offload the work of bundling to the browser and only needs to transform the source code into a native ES module before serving it to the browser. The appropriate source code is then only loaded by the browser when necessary – that is, if it is used on the currently displayed screen.

To avoid the inefficiency of re-bundling an entire application each time the source code changes, Vite supports HMR. Essentially, HMR is the practice of replacing only the ES module that was changed. This keeps the development server fast, whether the application consists of a single page or thousands.

So far, we’ve discussed Vite and its usage of esbuild, but how does Rollup fit in with it all? Vite utilizes Rollup during the build process – that is, instead of shipping the source code as is, our Svelte components are transformed into pure JS, which is then easily read by browsers. Rollup manages the potentially thousands of modules included in a project with features such as tree-shaking (only including parts of modules that are used), code splitting (breaking code up into chunks), and lazy loading (only loading resources when they are needed). The usage of these features leads to smaller, and therefore, better-performing web applications.

Who is this book for?

SvelteKit Up and Running is intended for web developers looking to advance their skill set by learning the next popular JS-based framework. Whether you’re deciding which JS framework should be the first you learn, or you want to set yourself apart from other job applicants by adding yet another popular technology to your résumé, this book will help provide you with all of the essentials to begin your journey to becoming a SvelteKit master! A working knowledge of HTML, CSS, JS, and Svelte will be required to maximize the value of this material.

What does this book cover?

Chapter 1, Initial Setup and Project Structure, explains how to install a new SvelteKit project and set up a development environment. It also covers how SvelteKit projects are logically structured and the best practices to organize source code.

Chapter 2, Configurations and Options, covers how to customize an application via the options available within SvelteKit and Vite configurations.

Chapter 3, Compatibility with Existing Standards, goes into detail about how SvelteKit works with modern web standards such as the Fetch, FormData, and URL Application Programming Interfaces (APIs).

Chapter 4, Effective Routing Techniques, discusses basic routing techniques. These techniques are essential to creating everything, from the simplest of pages and API endpoints to dynamic URLs that change with the content. It also covers how to create a cohesive user interface for applications using layouts.

Chapter 5, Deep Dive into Data Loading, explains in detail how to get data onto our pages and into components through the use of SvelteKit’s load() function. It also breaks down the data available to developers within that same function.

Chapter 6, Forms and Data Submission, covers how developers can receive data from users through the use of HTML form elements. From there, it explains how actions can be used to break up logic pertaining to forms and how those forms may be enhanced to reduce the friction often experienced by users.

Chapter 7, Advanced Routing Techniques, discusses the details behind some of the lesser-used yet more powerful features of SvelteKit’s routing mechanism. It covers how developers can work with optional parameters in routes, handle routes with an unknown number of parameters, as well as the precedence of routes when conflicts are encountered.

Chapter 8, Builds and Adapters, explains how developers can prepare an application for different environments. It provides examples to prepare a SvelteKit application for deployment to Cloudflare Pages, a Node.js environment, and even static hosting solutions.

Chapter 9, Hooks and Error Handling, covers the differences between server hooks and shared hooks, as well as how they can be used to manipulate data flowing into and out of an application. Along with this, it explains how developers can manage errors that are expected and what to do about those that were never anticipated.

Chapter 10, Managing Static Assets, goes into detail as to how to best manage assets such as images or global CSS files. It explains how Vite is central to this process and the best practices.

Chapter 11, Modules and Secrets, discusses a few of the modules not covered throughout the rest of the book. It gives you a general overview of some of the other tools and functionality that come bundled with SvelteKit. It also covers the modules responsible for managing secrets such as API keys or database passwords.

Chapter 12, Enhancing Accessibility and Optimizing SEO, will showcase how simple it is to make applications available to a wider audience. Not only does incorporating these practices make applications more compatible with technologies such as screen readers, but it also provides the added benefit of enhancing rankings within search engine providers.

Appendix: Examples and Support, gives you access to both official and unofficial community-maintained resources. The examples given of how to integrate other front-end technologies with SvelteKit show just how easy it is to do, especially when community projects are leveraged to speed up the development process. The resources provided in this section are invaluable for troubleshooting issues and making friends within the SvelteKit community.

To get the most out of this book

To get the most out of this book and ensure the information provided is retained, it is recommended to work alongside the material as you read it. Type the commands and code on your device, but also feel free to experiment and play with the code as you go. You will need a working knowledge of Svelte, JS, HTML, and CSS to get the most out of this book, as it focuses solely on SvelteKit.

Software/hardware covered in the book

Operating system requirements

SvelteKit 1.16.3 or higher

Windows, macOS, or Linux

JS

HTML and CSS

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/SvelteKit-Up-and-Running. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/1zRGE.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “In this new version, we still import the bcrypt module, but we’ve also added the import of user.json.”

A block of code is set as follows:

import bcrypt from 'bcrypt';
export const actions = {
  login: async ({request}) => {
    const form = await request.formData();
    const hash = bcrypt.hashSync(form.get('password'), 10);
    console.log(hash);
    console.log(crypto.randomUUID());
  }
}

Any command-line input or output is written as follows:

npm install bcrypt

Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “In Firefox, you can find it under Storage | Session Storage.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read SvelteKit Up and Running, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

  1. Scan the QR code or visit the link below

https://packt.link/free-ebook/9781804615485

  1. Submit your proof of purchase
  2. That’s it! We’ll send your free PDF and other benefits to your email directly
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.125.171