A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://kit.svelte.dev/docs/configuration below:

Configuration • Docs • Svelte

Your project’s configuration lives in a svelte.config.js file at the root of your project. As well as SvelteKit, this config object is used by other tooling that integrates with Svelte such as editor extensions.

svelte.config

import adapter from '@sveltejs/adapter-auto';

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

export default config;
Config

An extension of vite-plugin-svelte’s options.

interface Config extends SvelteConfig {}

Any additional options required by tooling that integrates with Svelte.

KitConfig

The kit property configures SvelteKit, and can have the following properties:

adapter

Your adapter is run when executing vite build. It determines how the output is converted for different platforms.

alias

An object containing zero or more aliases used to replace values in import statements. These aliases are automatically passed to Vite and TypeScript.

svelte.config

/** @type {import('@sveltejs/kit').Config} */
const config = {
	kit: {
		alias: {
			// this will match a file
			'my-file': 'path/to/my-file.js',

			// this will match a directory and its contents
			// (`my-directory/x` resolves to `path/to/my-directory/x`)
			'my-directory': 'path/to/my-directory',

			// an alias ending /* will only match
			// the contents of a directory, not the directory itself
			'my-directory/*': 'path/to/my-directory/*'
		}
	}
};

The built-in $lib alias is controlled by config.kit.files.lib as it is used for packaging.

You will need to run npm run dev to have SvelteKit automatically generate the required alias configuration in jsconfig.json or tsconfig.json.

appDir

The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes.

If paths.assets is specified, there will be two app directories — ${paths.assets}/${appDir} and ${paths.base}/${appDir}.

csp

Content Security Policy configuration. CSP helps to protect your users against cross-site scripting (XSS) attacks, by limiting the places resources can be loaded from. For example, a configuration like this...

svelte.config

/** @type {import('@sveltejs/kit').Config} */
const config = {
	kit: {
		csp: {
			directives: {
				'script-src': ['self']
			},
			// must be specified with either the `report-uri` or `report-to` directives, or both
			reportOnly: {
				'script-src': ['self'],
				'report-uri': ['/']
			}
		}
	}
};

export default config;

...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on mode) for any inline styles and scripts it generates.

To add a nonce for scripts and links manually included in src/app.html, you may use the placeholder %sveltekit.nonce% (for example <script nonce="%sveltekit.nonce%">).

When pages are prerendered, the CSP header is added via a <meta http-equiv> tag (note that in this case, frame-ancestors, report-uri and sandbox directives will be ignored).

When mode is 'auto', SvelteKit will use nonces for dynamically rendered pages and hashes for prerendered pages. Using nonces with prerendered pages is insecure and therefore forbidden.

Note that most Svelte transitions work by creating an inline <style> element. If you use these in your app, you must either leave the style-src directive unspecified or add unsafe-inline.

If this level of configuration is insufficient and you have more dynamic requirements, you can use the handle hook to roll your own CSP.

mode?: 'hash' | 'nonce' | 'auto';

Whether to use hashes or nonces to restrict <script> and <style> elements. 'auto' will use hashes for prerendered pages, and nonces for dynamically rendered pages.

directives?: CspDirectives;

Directives that will be added to Content-Security-Policy headers.

reportOnly?: CspDirectives;

Directives that will be added to Content-Security-Policy-Report-Only headers.

csrf

Protection against cross-site request forgery (CSRF) attacks.

Whether to check the incoming origin header for POST, PUT, PATCH, or DELETE form submissions and verify that it matches the server’s origin.

To allow people to make POST, PUT, PATCH, or DELETE requests with a Content-Type of application/x-www-form-urlencoded, multipart/form-data, or text/plain to your app from other origins, you will need to disable this option. Be careful!

embedded

Whether or not the app is embedded inside a larger app. If true, SvelteKit will add its event listeners related to navigation etc on the parent of %sveltekit.body% instead of window, and will pass params from the server rather than inferring them from location.pathname. Note that it is generally not supported to embed multiple SvelteKit apps on the same page and use client-side SvelteKit features within them (things such as pushing to the history state assume a single instance).

env

Environment variable configuration

The directory to search for .env files.

A prefix that signals that an environment variable is safe to expose to client-side code. See $env/static/public and $env/dynamic/public. Note that Vite’s envPrefix must be set separately if you are using Vite’s environment variable handling - though use of that feature should generally be unnecessary.

A prefix that signals that an environment variable is unsafe to expose to client-side code. Environment variables matching neither the public nor the private prefix will be discarded completely. See $env/static/private and $env/dynamic/private.

experimental

Experimental features. Here be dragons. These are not subject to semantic versioning, so breaking changes or removal can happen in any release.

Enables instrumentation.server.js for tracing and observability instrumentation.

remoteFunctions?: boolean;

Whether to enable the experimental remote functions feature. This feature is not yet stable and may be changed or removed at any time.

files

Where to find various files within your project.

the location of your source code

a place to put static files that should have stable URLs and undergo no processing, such as favicon.ico or manifest.json

The location of your client hooks.

The location of your server hooks.

The location of your universal hooks.

your app’s internal library, accessible throughout the codebase as $lib

the files that define the structure of your app (see Routing)

the location of your service worker’s entry point (see Service workers)

the location of the template for HTML responses

the location of the template for fallback error responses

inlineStyleThreshold

Inline CSS inside a <style> block at the head of the HTML. This option is a number that specifies the maximum length of a CSS file in UTF-16 code units, as specified by the String.length property, to be inlined. All CSS files needed for the page that are smaller than this value are merged and inlined in a <style> block.

This results in fewer initial requests and can improve your First Contentful Paint score. However, it generates larger HTML output and reduces the effectiveness of browser caches. Use it advisedly.

moduleExtensions

An array of file extensions that SvelteKit will treat as modules. Files with extensions that match neither config.extensions nor config.kit.moduleExtensions will be ignored by the router.

outDir

The directory that SvelteKit writes files to during dev and build. You should exclude this directory from version control.

output

Options related to the build output format

preloadStrategy?: 'modulepreload' | 'preload-js' | 'preload-mjs';

SvelteKit will preload the JavaScript modules needed for the initial page to avoid import ‘waterfalls’, resulting in faster application startup. There are three strategies with different trade-offs:

bundleStrategy?: 'split' | 'single' | 'inline';

The bundle strategy option affects how your app’s JavaScript and CSS files are loaded.

When using 'split', you can also adjust the bundling behaviour by setting output.experimentalMinChunkSize and output.manualChunks inside your Vite config’s build.rollupOptions.

If you want to inline your assets, you’ll need to set Vite’s build.assetsInlineLimit option to an appropriate size then import your assets through Vite.

vite.config

import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';

export default defineConfig({
	plugins: [sveltekit()],
	build: {
		// inline all imported assets
		assetsInlineLimit: Infinity
	}
});

src/routes/+layout

<script>
	// import the asset through Vite
	import favicon from './favicon.png';
</script>

<svelte:head>
	<!-- this asset will be inlined as a base64 URL -->
	<link rel="icon" href={favicon} />
</svelte:head>
<script lang="ts">
	// import the asset through Vite
	import favicon from './favicon.png';
</script>

<svelte:head>
	<!-- this asset will be inlined as a base64 URL -->
	<link rel="icon" href={favicon} />
</svelte:head>
paths
assets?: '' | `http://${string}` | `https://${string}`;

An absolute path that your app’s files are served from. This is useful if your files are served from a storage bucket of some kind.

base?: '' | `/${string}`;

A root-relative path that must start, but not end with / (e.g. /base-path), unless it is the empty string. This specifies where your app is served from and allows the app to live on a non-root path. Note that you need to prepend all your root-relative links with the base value or they will point to the root of your domain, not your base (this is how the browser works). You can use base from $app/paths for that: <a href="{base}/your-page">Link</a>. If you find yourself writing this often, it may make sense to extract this into a reusable component.

Whether to use relative asset paths.

If true, base and assets imported from $app/paths will be replaced with relative asset paths during server-side rendering, resulting in more portable HTML. If false, %sveltekit.assets% and references to build artifacts will always be root-relative paths, unless paths.assets is an external URL

Single-page app fallback pages will always use absolute paths, regardless of this setting.

If your app uses a <base> element, you should set this to false, otherwise asset URLs will incorrectly be resolved against the <base> URL rather than the current page.

In 1.0, undefined was a valid value, which was set by default. In that case, if paths.assets was not external, SvelteKit would replace %sveltekit.assets% with a relative path and use relative paths to reference build artifacts, but base and assets imported from $app/paths would be as specified in your config.

prerender

See Prerendering.

How many pages can be prerendered simultaneously. JS is single-threaded, but in cases where prerendering performance is network-bound (for example loading content from a remote CMS) this can speed things up by processing other tasks while waiting on the network response.

Whether SvelteKit should find pages to prerender by following links from entries.

entries?: Array<'*' | `/${string}`>;

An array of pages to prerender, or start crawling from (if crawl: true). The * string includes all routes containing no required [parameters] with optional parameters included as being empty (since SvelteKit doesn’t know what value any parameters should have).

handleHttpError?: PrerenderHttpErrorHandlerValue;

How to respond to HTTP errors encountered while prerendering the app.

svelte.config

/** @type {import('@sveltejs/kit').Config} */
const config = {
	kit: {
		prerender: {
			handleHttpError: ({ path, referrer, message }) => {
				// ignore deliberate link to shiny 404 page
				if (path === '/not-found' && referrer === '/blog/how-we-built-our-404-page') {
					return;
				}

				// otherwise fail the build
				throw new Error(message);
			}
		}
	}
};
handleMissingId?: PrerenderMissingIdHandlerValue;

How to respond when hash links from one prerendered page to another don’t correspond to an id on the destination page.

handleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue;

How to respond when an entry generated by the entries export doesn’t match the route it was generated from.

The value of url.origin during prerendering; useful if it is included in rendered content.

router
type?: 'pathname' | 'hash';

What type of client-side router to use.

resolution?: 'client' | 'server';

How to determine which route to load when navigating to a new page.

By default, SvelteKit will serve a route manifest to the browser. When navigating, this manifest is used (along with the reroute hook, if it exists) to determine which components to load and which load functions to run. Because everything happens on the client, this decision can be made immediately. The drawback is that the manifest needs to be loaded and parsed before the first navigation can happen, which may have an impact if your app contains many routes.

Alternatively, SvelteKit can determine the route on the server. This means that for every navigation to a path that has not yet been visited, the server will be asked to determine the route. This has several advantages:

The drawback is that for unvisited paths, resolution will take slightly longer (though this is mitigated by preloading).

When using server-side route resolution and prerendering, the resolution is prerendered along with the route itself.

serviceWorker typescript
config?: (config: Record<string, any>) => Record<string, any> | void;

A function that allows you to edit the generated tsconfig.json. You can mutate the config (recommended) or return a new one. This is useful for extending a shared tsconfig.json in a monorepo root, for example.

Note that any paths configured here should be relative to the generated config file, which is written to .svelte-kit/tsconfig.json.

version

Client-side navigation can be buggy if you deploy a new version of your app while people are using it. If the code for the new page is already loaded, it may have stale content; if it isn’t, the app’s route manifest may point to a JavaScript file that no longer exists. SvelteKit helps you solve this problem through version management. If SvelteKit encounters an error while loading the page and detects that a new version has been deployed (using the name specified here, which defaults to a timestamp of the build) it will fall back to traditional full-page navigation. Not all navigations will result in an error though, for example if the JavaScript for the next page is already loaded. If you still want to force a full-page navigation in these cases, use techniques such as setting the pollInterval and then using beforeNavigate:

+layout

<script>
	import { beforeNavigate } from '$app/navigation';
	import { updated } from '$app/state';

	beforeNavigate(({ willUnload, to }) => {
		if (updated.current && !willUnload && to?.url) {
			location.href = to.url.href;
		}
	});
</script>

If you set pollInterval to a non-zero value, SvelteKit will poll for new versions in the background and set the value of updated.current true when it detects one.

The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than Math.random() or Date.now().toString()), otherwise defaults to a timestamp of the build.

For example, to use the current commit hash, you could do use git rev-parse HEAD:

svelte.config

import * as child_process from 'node:child_process';

export default {
	kit: {
		version: {
			name: child_process.execSync('git rev-parse HEAD').toString().trim()
		}
	}
};

The interval in milliseconds to poll for version changes. If this is 0, no polling occurs.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4