Skip to main content

Référence

Modules

Éditer cette page sur Github

SvelteKit propose un certain nombre de modules que vous pouvez utiliser dans votre application.

$app/environment

ts
import { browser, building, dev, version } from '$app/environment';

browser

true if the app is running in the browser.

ts
const browser: boolean;

building

SvelteKit analyses your app during the build step by running it. During this process, building is true. This also applies during prerendering.

ts
const building: boolean;

dev

Whether the dev server is running. This is not guaranteed to correspond to NODE_ENV or MODE.

ts
const dev: boolean;

version

The value of config.kit.version.name.

ts
const version: string;

$app/forms

ts
import { applyAction, deserialize, enhance } from '$app/forms';

applyAction

This action updates the form property of the current page with the given data and updates $page.status. In case of an error, it redirects to the nearest error page.

ts
function applyAction<
Success extends Record<string, unknown> | undefined,
Failure extends Record<string, unknown> | undefined
>(
result: import('@sveltejs/kit').ActionResult<
Success,
Failure
>
): Promise<void>;

deserialize

Utilisez cette fonction pour désérialiser la réponse à une soumission de formulaire. Usage:

ts
import { deserialize } from '$app/forms';
async function handleSubmit(event) {
const response = await fetch('/form?/action', {
method: 'POST',
body: new FormData(event.target)
});
const result = deserialize(await response.text());
// ...
}
ts
function deserialize<
Success extends Record<string, unknown> | undefined,
Failure extends Record<string, unknown> | undefined
>(
result: string
): import('@sveltejs/kit').ActionResult<Success, Failure>;

enhance

Cette action améliore un élément <form> qui fonctionne même sans JavaScript.

La fonction submit est appelée à la soumission avec l'objet FormData donné et l'action qui doit être déclenchée. Si la fonction cancel est exécutée, le formulaire ne sera pas envoyé. Vous pouvez utiliser le controller d'annulation pour annuler la soumission dans le cas où une autre soumission démarre. Si une fonction est renvoyée, cette fonction est appelée avec la réponse du serveur. Si rien n'est renvoyé, le comportement par défaut sera utilisé.

Si cette fonction ou sa valeur de retour n'est pas définie, SvelteKit

  • met à jour par défaut la propriété form avec la donnée renvoyée si l'action est sur la même page que le formulaire
  • met à jour $page.status
  • réinitialise l'élément <form> et invalide toutes les données dans le cas où la soumission est réussie sans redirection
  • redirige en cas de réponse de redirection
  • redirige vers la page d'erreur la plus proche dans le cas d'une erreur inattendue

Si vous fournissez une fonction personnalisée avec un callback et voulez utiliser le comportement par défaut, exécutez update dans votre callback.

ts
function enhance<
Success extends Record<string, unknown> | undefined,
Failure extends Record<string, unknown> | undefined
>(
form_element: HTMLFormElement,
submit?: import('@sveltejs/kit').SubmitFunction<
Success,
Failure
>
): {
destroy(): void;
};

$app/navigation

ts
import {
afterNavigate,
beforeNavigate,
disableScrollHandling,
goto,
invalidate,
invalidateAll,
onNavigate,
preloadCode,
preloadData,
pushState,
replaceState
} from '$app/navigation';

afterNavigate

A lifecycle function that runs the supplied callback when the current component mounts, and also whenever we navigate to a new URL.

afterNavigate must be called during a component initialization. It remains active as long as the component is mounted.

ts
function afterNavigate(
callback: (
navigation: import('@sveltejs/kit').AfterNavigate
) => void
): void;

beforeNavigate

A navigation interceptor that triggers before we navigate to a new URL, whether by clicking a link, calling goto(...), or using the browser back/forward controls.

Calling cancel() will prevent the navigation from completing. If navigation.type === 'leave' — meaning the user is navigating away from the app (or closing the tab) — calling cancel will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user's response.

When a navigation isn't to a SvelteKit-owned route (and therefore controlled by SvelteKit's client-side router), navigation.to.route.id will be null.

If the navigation will (if not cancelled) cause the document to unload — in other words 'leave' navigations and 'link' navigations where navigation.to.route === nullnavigation.willUnload is true.

beforeNavigate must be called during a component initialization. It remains active as long as the component is mounted.

ts
function beforeNavigate(
callback: (
navigation: import('@sveltejs/kit').BeforeNavigate
) => void
): void;

disableScrollHandling

If called when the page is being updated following a navigation (in onMount or afterNavigate or an action, for example), this disables SvelteKit's built-in scroll handling. This is generally discouraged, since it breaks user expectations.

ts
function disableScrollHandling(): void;

goto

Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified url. For external URLs, use window.location = url instead of calling goto(url).

ts
function goto(
url: string | URL,
opts?:
| {
replaceState?: boolean | undefined;
noScroll?: boolean | undefined;
keepFocus?: boolean | undefined;
invalidateAll?: boolean | undefined;
state?: App.PageState | undefined;
}
| undefined
): Promise<void>;

invalidate

Causes any load functions belonging to the currently active page to re-run if they depend on the url in question, via fetch or depends. Returns a Promise that resolves when the page is subsequently updated.

If the argument is given as a string or URL, it must resolve to the same URL that was passed to fetch or depends (including query parameters). To create a custom identifier, use a string beginning with [a-z]+: (e.g. custom:state) — this is a valid URL.

The function argument can be used define a custom predicate. It receives the full URL and causes load to rerun if true is returned. This can be useful if you want to invalidate based on a pattern instead of a exact match.

ts
// Example: Match '/path' regardless of the query parameters
import { invalidate } from '$app/navigation';
invalidate((url) => url.pathname === '/path');
ts
function invalidate(
resource: string | URL | ((url: URL) => boolean)
): Promise<void>;

invalidateAll

Causes all load functions belonging to the currently active page to re-run. Returns a Promise that resolves when the page is subsequently updated.

ts
function invalidateAll(): Promise<void>;

onNavigate

A lifecycle function that runs the supplied callback immediately before we navigate to a new URL except during full-page navigations.

If you return a Promise, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use document.startViewTransition. Avoid promises that are slow to resolve, since navigation will appear stalled to the user.

If a function (or a Promise that resolves to a function) is returned from the callback, it will be called once the DOM has updated.

onNavigate must be called during a component initialization. It remains active as long as the component is mounted.

ts
function onNavigate(
callback: (
navigation: import('@sveltejs/kit').OnNavigate
) => MaybePromise<(() => void) | void>
): void;

preloadCode

Programmatically imports the code for routes that haven't yet been fetched. Typically, you might call this to speed up subsequent navigation.

You can specify routes by any matching pathname such as /about (to match src/routes/about/+page.svelte) or /blog/* (to match src/routes/blog/[slug]/+page.svelte).

Unlike preloadData, this won't call load functions. Returns a Promise that resolves when the modules have been imported.

ts
function preloadCode(pathname: string): Promise<void>;

preloadData

Programmatically preloads the given page, which means

  1. ensuring that the code for the page is loaded, and
  2. calling the page's load function with the appropriate options.

This is the same behaviour that SvelteKit triggers when the user taps or mouses over an <a> element with data-sveltekit-preload-data. If the next navigation is to href, the values returned from load will be used, making navigation instantaneous. Returns a Promise that resolves with the result of running the new route's load functions once the preload is complete.

ts
function preloadData(href: string): Promise<
| {
type: 'loaded';
status: number;
data: Record<string, any>;
}
| {
type: 'redirect';
location: string;
}
>;

pushState

Programmatically create a new history entry with the given $page.state. To use the current URL, you can pass '' as the first argument. Used for shallow routing.

ts
function pushState(
url: string | URL,
state: App.PageState
): void;

replaceState

Programmatically replace the current history entry with the given $page.state. To use the current URL, you can pass '' as the first argument. Used for shallow routing.

ts
function replaceState(
url: string | URL,
state: App.PageState
): void;

$app/paths

ts
import { assets, base, resolveRoute } from '$app/paths';

assets

An absolute path that matches config.kit.paths.assets.

If a value for config.kit.paths.assets is specified, it will be replaced with '/_svelte_kit_assets' during vite dev or vite preview, since the assets don't yet live at their eventual URL.

ts
let assets:
| ''
| `https://${string}`
| `http://${string}`
| '/_svelte_kit_assets';

base

A string that matches config.kit.paths.base.

Example usage: <a href="{base}/your-page">Link</a>

ts
let base: '' | `/${string}`;

resolveRoute

Populate a route ID with params to resolve a pathname.

ts
function resolveRoute(
id: string,
params: Record<string, string | undefined>
): string;

$app/server

ts
import { read } from '$app/server';

read

Importe un fichier statique lu depuis le disque

ts
function read(asset: string): Response;

$app/stores

ts
import { getStores, navigating, page, updated } from '$app/stores';

getStores

ts
function getStores(): {
page: typeof page;
navigating: typeof navigating;
updated: typeof updated;
};

navigating

Un store de lecture. Lorsque la navigation démarre, la valeur de ce store est un objet Navigation avec les propriétés from, to, type et (si type === 'popstate') delta. Lorsque la navigation se termine, la valeur de ce store revient à null.

Sur le serveur, il est uniquement possible de s'abonner à ce store pendant l'initialisation du composant. Dans le navigateur, vous pouvez vous y abonner à tout moment.

ts
const navigating: import('svelte/store').Readable<
import('@sveltejs/kit').Navigation | null
>;

page

Un store de lecture dont la valeur contient les données de page.

Sur le serveur, il est uniquement possible de s'abonner à ce store pendant l'initialisation du composant. Dans le navigateur, vous pouvez vous y abonner à tout moment.

ts
const page: import('svelte/store').Readable<
import('@sveltejs/kit').Page
>;

updated

Un store de lecture dont la valeur initiale est false. Si version.pollInterval est une valeur différente de zéro, SvelteKit va vérifier si une nouvelle version de l'application est disponible et mettre à jour la valeur du store à true lorsque c'est le cas. updated.check() va forcer une vérification immédiate, peu importe la valeur de version.pollInterval.

Sur le serveur, il est uniquement possible de s'abonner à ce store pendant l'initialisation du composant. Dans le navigateur, vous pouvez vous y abonner à tout moment.

ts
const updated: import('svelte/store').Readable<boolean> & {
check(): Promise<boolean>;
};

$env/dynamic/private

Ce module fournit un accès aux variables d'environnement d'exécution, tel que défini par votre plateforme d'exécution. Par exemple, si vous utilisez adapter-node (ou si vous lancez vite preview), ceci est équivalent à process.env. Ce module inclut uniquement les variables dont le nom ne commence pas par config.kit.env.publicPrefix et commence par config.kit.env.privatePrefix (si configuré)

Ce module ne peut pas être importé côté client.

Dynamic environment variables cannot be used during prerendering.

ts
import { env } from '$env/dynamic/private';
console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE);

En mode dev, $env/dynamic inclut toujours les variables d'environnement de .env. En prod, ce comportement dépend de votre adaptateur.

$env/dynamic/public

Similaire à $env/dynamic/private, mais inclut uniquement les variables dont le nom commence par config.kit.env.publicPrefix (qui vaut par défaut PUBLIC_), et peuvent donc être exposées dans le code client en toute sécurité.

Notez que les variables d'environnement dynamiques doivent toutes être envoyées depuis le serveur vers le client, impliquant des requêtes plus conséquentes – lorsque c'est possible, utilisez plutôt $env/static/public.

Dynamic environment variables cannot be used during prerendering.

ts
import { env } from '$env/dynamic/public';
console.log(env.PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE);

$env/static/private

Les variables d'environnement chargées par Vite depuis les fichiers .env et process.env. À l'instar de $env/dynamic/private, ce module ne peut pas être importé dans du code côté client. Ce module inclut uniquement les variables dont le nom ne commence pas par config.kit.env.publicPrefix et commence par config.kit.env.privatePrefix (si configuré).

À la différence de $env/dynamic/private, les valeurs exportées depuis ce module sont injectées de manière statique dans votre code généré au moment de la compilation, permettant des optimisations telles que la suppression de code mort.

ts
import { API_KEY } from '$env/static/private';

Notez que toutes les variables d'environnement référencées dans votre code doivent être déclarées (par exemple dans un fichier .env), même si elles n'ont pas de valeur tant que l'application n'est pas déployée :

MY_FEATURE_FLAG=""

Vous pouvez écrasez les valeurs du fichier .env depuis la ligne de commande de cette manière :

MY_FEATURE_FLAG="enabled" npm run dev

$env/static/public

Similaire à $env/static/private, mais inclut uniquement les variables d'environnement qui commencent par config.kit.env.publicPrefix (qui vaut par défaut PUBLIC_), et peuvent donc être exposées dans le code client en toute sécurité.

Les valeurs sont remplacées de manière statique au moment de la compilation.

ts
import { PUBLIC_BASE_URL } from '$env/static/public';

$lib

Ceci est un simple alias vers src/lib, ou tout dossier spécifié par config.kit.files.lib. Cela vous permet d'accéder aux composants et utilitaires communs sans l'aberration ../../../../.

$lib/server

Un sous-dossier de $lib. SvelteKit vous empêche d'importer les modules de $lib/server dans votre code client. Voir la section Modules réservés serveur.

$service-worker

ts
import { base, build, files, prerendered, version } from '$service-worker';

Ce module est uniquement disponible dans les service workers

base

Le chemin de base de déploiement. Ceci est équivalent à config.kit.paths.base, mais est calculé en utilisant location.pathname, ce qui implique que cela continuera à fonctionner correctement si le site est déployé dans un sous-dossier. Notez qu'il y a une base mais pas d'assets, puisque les service workers ne peuvent pas être utilisés si config.kit.paths.assets est précisé.

ts
const base: string;

build

Un tableau d'URLs représentant les fichiers générés par Vite, pouvant être mises en cache avec cache.addAll(build). Pendant le développement, ceci est un tableau vide.

ts
const build: string[];

files

Un tableau d'URLs représentant les fichiers dans votre dossier static, ou celui précisé par config.kit.files.assets. Vous pouvez personnaliser les fichiers qui sont inclus dans le dossier static en utilisant config.kit.serviceWorker.files.

ts
const files: string[];

prerendered

Un tableau de chemins correspondant aux pages et endpoints prérendus. Pendant le développement, ceci est un tableau vide.

ts
const prerendered: string[];

version

Voir config.kit.version. Ceci est utile pour générer des noms de cache uniques dans votre service worker, afin qu'un déploiement ultérieur de votre application puisse invalider les anciens caches.

ts
const version: string;

@sveltejs/kit

ts
import {
VERSION,
error,
fail,
isHttpError,
isRedirect,
json,
redirect,
text
} from '@sveltejs/kit';

VERSION

ts
const VERSION: string;

error

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.

ts
function error(status: number, body: App.Error): never;

error

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.

ts
function error(
status: number,
body?: {
message: string;
} extends App.Error
? App.Error | string | undefined
: never
): never;

fail

Create an ActionFailure object.

ts
function fail(status: number): ActionFailure<undefined>;

fail

Crée un objet ActionFailure.

ts
function fail<
T extends Record<string, unknown> | undefined = undefined
>(status: number, data: T): ActionFailure<T>;

isHttpError

Checks whether this is an error thrown by error.

ts
function isHttpError<T extends number>(
e: unknown,
status?: T | undefined
): e is HttpError_1 & {
status: T extends undefined ? never : T;
};

isRedirect

Checks whether this is a redirect thrown by redirect.

ts
function isRedirect(e: unknown): e is Redirect_1;

json

Crée un objet Response en JSON à partir des données fournies.

ts
function json(
data: any,
init?: ResponseInit | undefined
): Response;

redirect

Redirige une requête. Si appelé pendant le traitement d'une requête, Sveltekit va retourner une réponse de redirection. Assurez-vous de ne pas "attraper" la redirection levée, ce qui empêcherait SvelteKit de la gérer.

ts
function redirect(
status:
| 300
| 301
| 302
| 303
| 304
| 305
| 306
| 307
| 308
| ({} & number),
location: string | URL
): never;

text

Crée un objet Response à partir du body fournit.

ts
function text(
body: string,
init?: ResponseInit | undefined
): Response;

@sveltejs/kit/hooks

ts
import { sequence } from '@sveltejs/kit/hooks';

sequence

Une fonction utilitaire pour orchestrer plusieurs appels à handle à la manière d'un middleware. Le comportement des options de handle est le suivant :

  • transformPageChunk s'applique dans l'ordre inverse et ses résultats sont fusionnés
  • preload s'applique dans l'ordre normal, la première option "gagne" et aucune option preload ne sera appelée après celle-ci
  • filterSerializedResponseHeaders fonctionne comme preload
src/hooks.server.js
ts
import { sequence } from '@sveltejs/kit/hooks';
/// type: import('@sveltejs/kit').Handle
Binding element 'html' implicitly has an 'any' type.7031Binding element 'html' implicitly has an 'any' type.
async function first({ event, resolve }) {
console.log('first pre-processing');
const result = await resolve(event, {
transformPageChunk: ({ html }) => {
// les transformations sont appliquées dans l'ordre inverse
console.log('first transform');
return html;
},
preload: () => {
// cette option gagne puisque c'est la première définie dans la chaîne
console.log('first preload');
}
});
console.log('first post-processing');
return result;
Binding element 'event' implicitly has an 'any' type.
Binding element 'resolve' implicitly has an 'any' type.
7031
7031
Binding element 'event' implicitly has an 'any' type.
Binding element 'resolve' implicitly has an 'any' type.
}
/// type: import('@sveltejs/kit').Handle
Binding element 'html' implicitly has an 'any' type.7031Binding element 'html' implicitly has an 'any' type.
async function second({ event, resolve }) {
console.log('second pre-processing');
const result = await resolve(event, {
transformPageChunk: ({ html }) => {
console.log('second transform');
return html;
},
preload: () => {
console.log('second préchargement');
},
filterSerializedResponseHeaders: () => {
// cette option gagne puisque c'est la première définie dans la chaîne
console.log('second filterSerializedResponseHeaders');
}
});
console.log('second post-processing');
return result;
}
export const handle = sequence(first, second);
src/hooks.server.ts
ts
import { sequence } from '@sveltejs/kit/hooks';
/// type: import('@sveltejs/kit').Handle
Binding element 'html' implicitly has an 'any' type.7031Binding element 'html' implicitly has an 'any' type.
async function first({ event, resolve }) {
console.log('first pre-processing');
const result = await resolve(event, {
transformPageChunk: ({ html }) => {
// les transformations sont appliquées dans l'ordre inverse
console.log('first transform');
return html;
},
preload: () => {
// cette option gagne puisque c'est la première définie dans la chaîne
console.log('first preload');
},
});
console.log('first post-processing');
return result;
Binding element 'event' implicitly has an 'any' type.
Binding element 'resolve' implicitly has an 'any' type.
7031
7031
Binding element 'event' implicitly has an 'any' type.
Binding element 'resolve' implicitly has an 'any' type.
}
/// type: import('@sveltejs/kit').Handle
Binding element 'html' implicitly has an 'any' type.7031Binding element 'html' implicitly has an 'any' type.
async function second({ event, resolve }) {
console.log('second pre-processing');
const result = await resolve(event, {
transformPageChunk: ({ html }) => {
console.log('second transform');
return html;
},
preload: () => {
console.log('second préchargement');
},
filterSerializedResponseHeaders: () => {
// cette option gagne puisque c'est la première définie dans la chaîne
console.log('second filterSerializedResponseHeaders');
},
});
console.log('second post-processing');
return result;
}
export const handle = sequence(first, second);

L'exemple ci-dessus affichera :

first pre-processing
first preload
second pre-processing
second filterSerializedResponseHeaders
second transform
first transform
second post-processing
first post-processing
ts
function sequence(
...handlers: import('@sveltejs/kit').Handle[]
): import('@sveltejs/kit').Handle;

@sveltejs/kit/node

ts
import {
createReadableStream,
getRequest,
setResponse
} from '@sveltejs/kit/node';

createReadableStream

Converts a file on disk to a readable stream

ts
function createReadableStream(file: string): ReadableStream;

getRequest

ts
function getRequest({
request,
base,
bodySizeLimit
}: {
request: import('http').IncomingMessage;
base: string;
bodySizeLimit?: number;
}): Promise<Request>;

setResponse

ts
function setResponse(
res: import('http').ServerResponse,
response: Response
): Promise<void>;

@sveltejs/kit/node/polyfills

ts
import { installPolyfills } from '@sveltejs/kit/node/polyfills';

installPolyfills

Rend ces APIs web disponibles en tant que variables globales :

  • crypto
  • File
ts
function installPolyfills(): void;

@sveltejs/kit/vite

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

sveltekit

Renvoie les plugins Vite de SvelteKit.

ts
function sveltekit(): Promise<import('vite').Plugin[]>;
précédent CLI
suivant Types