2

Configurations and Options

In my opinion, there are few things more frustrating than working diligently on a project for weeks, only for a bug to manifest itself upon the project launch in the production environment because of a seemingly obscure configuration option. That is why this chapter will make efforts to teach you about the various options available to you before you dig in. I know you’re ready to learn about SvelteKit already. I promise that I’m just as excited to get into “actually building stuff” as you are, but I assure you that there is value in learning these concepts early on. If you’re hoping to rapidly develop a high-performance web application, then I believe it is in your best interest to learn these concepts before you start on your specific app.

To begin this chapter, we’ll start by taking a look at how you can manage your project configuration with options available in your svelte.config.js file. We’ll then take a brief look at some configurations with basic adapters so that you can get started. We’ll also look at the options available to you in your vite.config.js file. It may seem strange to discuss Vite so much in a book about SvelteKit, but SvelteKit wouldn’t be the tool it is without Vite.

In this chapter, we’ll cover these topics:

  • Configuring SvelteKit
  • Configuring Vite

After we have discussed the configurations and how they’ll affect your tools, you should feel more comfortable making appropriate changes to suit the needs of your next SvelteKit 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/chapter02

Configuring SvelteKit

The essential configuration for a SvelteKit project lives inside the svelte.config.js file. Understanding the various options available to you will empower you to make the most of SvelteKit. While we cannot cover all available options in such a brief section, the aim of it is to cover options that you are likely to find useful. For more configuration options, see the Further Reading section at the end of this chapter for more resources.

To get started, go ahead and open the svelte.config.js file from the skeleton project in your editor. Note that it’s quite simple at this point. Essentially, it imports the adapter function from the @sveltejs/adapter-auto package, specifies that function in the kit property of the config constant, and finally, exports the config object. We’re also given a type annotation via JSDoc. The config.kit property is where we will add various other properties to customize our configuration. It should look similar to this:

import adapter from '@sveltejs/adapter-auto';
/** @type {import('@sveltejs/kit').Config} */
const config = {
      kit: {
           adapter: adapter()
       }
};
export default config;

The adapter-auto package is included by default when installing with npm create svelte@latest. It will automatically adapt your project during build time so that it can be effortlessly deployed to Vercel, Cloudflare Pages, Netlify, or Azure Static Web Apps. Because of this, adapter-auto is considered a zero-config adapter, meaning that you can use it for any of the aforementioned environments. However, even if you are using one of these environments, it is recommended to install the environment-specific adapter to your devDependencies. Doing so will allow you to customize options specific to that environment, since adapter-auto does not accept any options.

We’ll discuss adapters at length in a later chapter; we’ll cover how you can use the adapter-static package to generate a static site and how you can run SvelteKit applications on Node.js servers using adapter-node. For now, let’s look at some other potential configuration options you may find yourself needing in the following sections.

alias

While it is very useful to have access to the src/lib/ path via the $lib/ alias, there may come a time where you want to access something outside of that. To do so, you can add the alias property to config.kit. For instance, if your project had a specific file for connecting to and managing a database, you could create an alias to make imports simpler. Alternatively, you may want to easily access an image from a commonly used folder. See the following code snippets demonstrating these concepts:

src/db.js

const db = {
     connection: 'DB connection successful!',
     // database logic goes here…
};
export default db;

svelte.config.js

import adapter from '@sveltejs/adapter-auto';
/** @type {import('@sveltejs/kit').Config} */
const config = {
      kit: {
           adapter: adapter(),
           alias: {
                 db: '/src/db.js',
                 img: '/src/images'
                 }
       },
};
export default config;

src/routes/+page.svelte

<script>
      import db from 'db';
      import url from 'img/demo.png';
      let status = db.connection;
</script>
<p>{status}</p>
<img src={url}>

In this example, I’ve created a mock database object with a property called connection. In the svelte.config.js file, I’ve added two aliases – one for the mock database object and another that points to a folder of images. Then, in the +page.svelte file, an import is made from both of these aliases to illustrate how you might use aliases to import a single file, as well as make an import of one particular file from a directory.

This example fails to take into consideration any asynchronous code that would usually be required for database operations. It is also not considered best practice to make calls to a database directly from routes, but we’ll come back to how to do that in a later chapter. While this example is quite rudimentary, it is intended to showcase the usefulness of being able to add your own aliases for specific files and directories.

appDir

This property defaults to the _app value and is used to determine where imported assets such as CSS and JS will be served from the built application.

csp

To aid in defending your application and its users from malicious cross-site scripting (XSS) attacks, you can implement Content Security Policy (CSP) response headers. How CSP works is beyond the scope of this book, so it is recommended to study it further before implementing these options in your configuration, as doing so without sufficient knowledge can lead to undesired consequences. The three properties that can be added to config.kit.csp are as follows:

  • mode: 'hash' | 'nonce' | 'auto': This specifies whether hashes or nonces should be used to enforce CSP. Using auto will use nonces for dynamically rendered pages and hashes for prerendered pages.
  • directives: Directives specified here will be added to the Content-Security-Policy headers. See the official SvelteKit documentation for a full list of available options.
  • reportOnly: This is used to report errors but still allows scripts to be loaded. Directives specified here will be added to the Content-Security-Policy-Report-Only headers. See the official SvelteKit documentation for a full list of available options.

While this can be helpful to prevent scripts from being loaded from external sources, you may have deliberately included scripts from a Content Delivery Network (CDN). If you have included external scripts, then depending on the CSP for your application, you may need to add %sveltekit.nonce% to the nonce property of the included script, like so:

<script src='YOUR_EXT_URL/script.js' nonce='%sveltekit.nonce%'>

csrf

To help protect your application from cross-site request forgery (CSRF) attacks, this option comes enabled by default. It prevents end users from making POST requests to your application from another origin. If you need to disable it, you can do so by setting config.kit.csrf.checkOrigin to false, like so:

const config = {
  kit: {
    adapter: adapter(),
    csrf: {
      checkOrigin: false
    }
  },
};

env

If you have included .env files in your project, you can further specify which ones can be public and which directory they are stored in with the following options:

  • dir: A string value that defaults to “.” (the project root directory).
  • publicPrefix: A string value that defaults to PUBLIC_. This prefix denotes whether environment variables located in .env files are safe to be exposed to client-side code. Those environment variables are then accessible by importing from the $env/static/public module throughout the rest of the application. For example, assume we’re working with an .env file in the base directory of our project. Adding the PUBLIC_EXTERNAL_API=https://api.nasa.gov/planetary/apod value will be importable in client-side code, whereas the INTERNAL_API=AN_INTERNAL_IP_ADDRESS value will only be importable in server code.

prerender

It’s very likely that at least some content in your application will be prerenderable – that is, it will show the exact same HTML, CSS, and JS for each and every user that visits it. A common example of this is an “About” page. Whether or not you would like for a specific page to be prerendered will be addressed in a later chapter, but to further customize prerendering, consider the following options that can be added to config.kit.prerender:

  • entries: An array of strings for each route that should be prerendered. The default value is the * special character and will include all non-dynamic routes.
  • concurrency: The number of pages that can be prerendered simultaneously. Because JS is single-threaded, this will only take effect if your project needs to make network requests during the prerendering process.
  • crawl: This option defaults to true. It tells SvelteKit whether or not it should prerender pages found in the entries array.
  • handleHttpError: This option defaults to fail. Other options include ignore, warn, or a details object specific to SvelteKit that implements PrerenderHttpErrorHandler. If the prerendering process fails at any point, this option determines how to manage it.
  • handleMissingId: This is the same as handleHttpError except that the details object it accepts is implemented from PrerenderMissingIdHandler. Linking to a specific point on another page is done using a hash in the URL – a # character followed by the ID of an element on the destination page. If an element with the specified ID is not found on the destination page, then this option will determine how the build process should behave.
  • origin: This defaults to https://kit.svelte.dev/docs/page-options. If you want to use the application URL in the rendered content, it can be helpful to specify it here.

Hopefully, this list of options was not too overwhelming and gave some insight as to how you can customize SvelteKit to your needs. SvelteKit will continue to evolve, so it is always recommended to check the official documentation, as features may be added or removed in future releases.

Now that we’ve looked at a few options available for customizing SvelteKit, let’s look at how we can modify the behavior of Vite. Like SvelteKit, Vite comes with opinions on how projects should be configured. These opinions are useful for a wide range of use cases, but there will always be instances where they’ll need to be adjusted.

Configuring Vite

As previously mentioned, Vite is the build tool that makes SvelteKit possible, so it’s just as important to know how to configure Vite as it is SvelteKit. That being said, Vite is highly configurable, and so for the sake of brevity (and your attention span), we’ll keep it limited to only a high-level view of available options. This section is not intended to be an exhaustive list but rather a quick glance at the options available to you. For further reading, consult the resources located at the end of this chapter.

At its heart, SvelteKit is just a Vite plugin. Obviously, there is more to it than that, but when you open vite.config.js in a newly created SvelteKit project, you’ll see what I mean. Similar to svelte.config.js, this configuration exports a config constant, with a couple of properties set – the SvelteKit plugin that is imported and the tests to include. If you answered “no” to tests during the create@svelte prompts, you may not see the test property. The configuration from the skeleton application is shown in the following code snippet:

import { sveltekit } from '@sveltejs/kit/vite';
const config = {
      plugins: [sveltekit()],
      test: {
           include: ['src/**/*.{test,spec}.{js,ts}']
     }
};
export default config;

plugins

It seems logical to start with the plugins property of our Vite configuration, as this book’s entire premise is based around one plugin in particular. With Vite becoming more popular and seeing a rise in adoption, its ecosystem is expanding, and with that comes more plugins. Many of those plugins are developed by the community to solve common problems. And because Vite extends Rollup, many Rollup plugins also work with Vite out of the box, although not all. The Vite development team maintains several official Vite plugins, including one that enables legacy browser support. Many features and functionality can be added to your application via these plugins. Once you have found a plugin that satisfies your requirements and installed it, you will need to import and include it in the config.plugins array, just as SvelteKit was previously shown. Configurations for plugins vary, but typically, options are passed via the parameters of the imported function call. To find more plugins available for Vite, check out the Awesome Vite project at https://github.com/vitejs/awesome-vite.

server

Since Vite is running the development server you’ll be working on with SvelteKit, you may need to make some changes to how that server operates. For instance, you may need to change the default port, proxy it through another server elsewhere, add support for HTTPS, or even disable HMR for testing with older browsers. In these instances and more, you will want to adjust config.server accordingly.

build

When building your application for your production environment, you’ll likely need to make some adjustments. Whether you need to ensure the application has met specific browser compatibility or you’d like to customize Rollup’s options, these settings can be found under config.build.

preview

Once you have built your application for your production environment, you should test it with Vite’s preview functionality. Changing your preview server’s options can be done by managing config.preview.

optimizeDeps

Occasionally, you may want to test multiple dependencies or versions of dependencies with your code to see how well they work for your project. To include or exclude dependencies from pre-bundling, or to further modify options used by esbuild, begin configuring config.optimizeDeps.

ssr

If you need to prevent dependencies from running in your server environment, you may need to manage the options available to you under config.ssr.

Summary

In this chapter, we covered many configuration options available for SvelteKit. We went over an example of how config.kit.alias might be useful for importing frequently accessed files. While we did not cover all options, we did briefly look at the appDir, csp, csrf, env, and prerender options and how they can affect our application.

We also glanced at some configuration options available in vite.config.js. For the most part, SvelteKit sets up a configuration that works for us according to the choices made in the installation prompt, but for further tweaks and plugins, we now know where to start looking in the official Vite documentation.

In the next chapter, we’ll go over some existing web standards and how SvelteKit’s design keeps them in mind. Existing standards present in web browsers are quickly becoming supported in other environments, including Node-based environments or even Deno and Cloudflare Workers. By leveraging these standards instead of building new ones on top of them, SvelteKit is accessible to more developers.

Further Reading

  • SvelteKit documentation – The first stop on your troubleshooting journey should always be the official SvelteKit documentation: https://kit.svelte.dev/docs
  • Awesome Vite – A collection of official and community-maintained resources or plugins that make development with Vite delightful: https://github.com/vitejs/awesome-vite
  • Vite documentation – Need to modify your development server or build process? Check here for official recommendations: https://vitejs.dev/config/
..................Content has been hidden....................

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