Référence
Modules
Éditer cette page sur GithubSvelteKit propose un certain nombre de modules que vous pouvez utiliser dans votre application.
$app/environmentpermalink
ts
import {browser ,building ,dev ,version } from '$app/environment';
browserpermalink
true
if the app is running in the browser.
ts
constbrowser : boolean;
buildingpermalink
SvelteKit analyses your app during the build
step by running it. During this process, building
is true
. This also applies during prerendering.
ts
constbuilding : boolean;
devpermalink
Whether the dev server is running. This is not guaranteed to correspond to NODE_ENV
or MODE
.
ts
constdev : boolean;
versionpermalink
The value of config.kit.version.name
.
ts
constversion : string;
$app/formspermalink
ts
import {applyAction ,deserialize ,enhance } from '$app/forms';
applyActionpermalink
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
functionapplyAction <Success extendsRecord <string, unknown> | undefined,Failure extendsRecord <string, unknown> | undefined>(result : import('@sveltejs/kit').ActionResult <Success ,Failure >):Promise <void>;
deserializepermalink
Utilisez cette fonction pour désérialiser la réponse à une soumission de formulaire. Usage:
ts
import {deserialize } from '$app/forms';async functionhandleSubmit (event ) {constresponse = awaitfetch ('/form?/action', {method : 'POST',body : newFormData (event .target )});constresult =deserialize (awaitresponse .text ());// ...}
ts
functiondeserialize <Success extendsRecord <string, unknown> | undefined,Failure extendsRecord <string, unknown> | undefined>(result : string): import('@sveltejs/kit').ActionResult <Success ,Failure >;
enhancepermalink
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
functionenhance <Success extendsRecord <string, unknown> | undefined,Failure extendsRecord <string, unknown> | undefined>(form_element :HTMLFormElement ,submit ?: import('@sveltejs/kit').SubmitFunction <Success ,Failure >): {destroy (): void;};
$app/navigationpermalink
ts
import {afterNavigate ,beforeNavigate ,disableScrollHandling ,goto ,invalidate ,invalidateAll ,onNavigate ,preloadCode ,preloadData ,pushState ,replaceState } from '$app/navigation';
afterNavigatepermalink
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
functionafterNavigate (callback : (navigation : import('@sveltejs/kit').AfterNavigate ) => void): void;
beforeNavigatepermalink
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 === null
— navigation.willUnload
is true
.
beforeNavigate
must be called during a component initialization. It remains active as long as the component is mounted.
ts
functionbeforeNavigate (callback : (navigation : import('@sveltejs/kit').BeforeNavigate ) => void): void;
disableScrollHandlingpermalink
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
functiondisableScrollHandling (): void;
gotopermalink
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
functiongoto (url : string |URL ,opts ?:| {replaceState ?: boolean | undefined;noScroll ?: boolean | undefined;keepFocus ?: boolean | undefined;invalidateAll ?: boolean | undefined;state ?:App .PageState | undefined;}| undefined):Promise <void>;
invalidatepermalink
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 parametersimport {invalidate } from '$app/navigation';invalidate ((url ) =>url .pathname === '/path');
ts
functioninvalidate (resource : string |URL | ((url :URL ) => boolean)):Promise <void>;
invalidateAllpermalink
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
functioninvalidateAll ():Promise <void>;
onNavigatepermalink
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
functiononNavigate (callback : (navigation : import('@sveltejs/kit').OnNavigate ) =>MaybePromise <(() => void) | void>): void;
preloadCodepermalink
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
functionpreloadCode (pathname : string):Promise <void>;
preloadDatapermalink
Programmatically preloads the given page, which means
- ensuring that the code for the page is loaded, and
- 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
functionpreloadData (href : string):Promise <| {type : 'loaded';status : number;data :Record <string, any>;}| {type : 'redirect';location : string;}>;
pushStatepermalink
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
functionpushState (url : string |URL ,state :App .PageState ): void;
replaceStatepermalink
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
functionreplaceState (url : string |URL ,state :App .PageState ): void;
$app/pathspermalink
ts
import {assets ,base ,resolveRoute } from '$app/paths';
assetspermalink
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'
duringvite dev
orvite preview
, since the assets don't yet live at their eventual URL.
ts
letassets :| ''| `https://${string}`| `http://${string}`| '/_svelte_kit_assets';
basepermalink
A string that matches config.kit.paths.base
.
Example usage: <a href="{base}/your-page">Link</a>
ts
letbase : '' | `/${string}`;
resolveRoutepermalink
Populate a route ID with params to resolve a pathname.
ts
functionresolveRoute (id : string,params :Record <string, string | undefined>): string;
$app/serverpermalink
ts
import {read } from '$app/server';
readpermalink
Importe un fichier statique lu depuis le disque
ts
functionread (asset : string):Response ;
$app/storespermalink
ts
import {getStores ,navigating ,page ,updated } from '$app/stores';
getStorespermalink
ts
functiongetStores (): {page : typeofpage ;navigating : typeofnavigating ;updated : typeofupdated ;};
navigatingpermalink
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
constnavigating : import('svelte/store').Readable <import('@sveltejs/kit').Navigation | null>;
pagepermalink
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
constpage : import('svelte/store').Readable <import('@sveltejs/kit').Page >;
updatedpermalink
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
constupdated : import('svelte/store').Readable <boolean> & {check ():Promise <boolean>;};
$env/dynamic/privatepermalink
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
. Enprod
, ce comportement dépend de votre adaptateur.
$env/dynamic/publicpermalink
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/privatepermalink
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/publicpermalink
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';
$libpermalink
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/serverpermalink
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-workerpermalink
ts
import {base ,build ,files ,prerendered ,version } from '$service-worker';
Ce module est uniquement disponible dans les service workers
basepermalink
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
constbase : string;
buildpermalink
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
constbuild : string[];
filespermalink
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
constfiles : string[];
prerenderedpermalink
Un tableau de chemins correspondant aux pages et endpoints prérendus. Pendant le développement, ceci est un tableau vide.
ts
constprerendered : string[];
versionpermalink
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
constversion : string;
@sveltejs/kitpermalink
ts
import {VERSION ,error ,fail ,isHttpError ,isRedirect ,json ,redirect ,text } from '@sveltejs/kit';
VERSIONpermalink
ts
constVERSION : string;
errorpermalink
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
functionerror (status : number,body :App .Error ): never;
errorpermalink
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
functionerror (status : number,body ?: {message : string;} extendsApp .Error ?App .Error | string | undefined: never): never;
failpermalink
Create an ActionFailure
object.
ts
functionfail (status : number):ActionFailure <undefined>;
failpermalink
Crée un objet ActionFailure
.
ts
functionfail <T extendsRecord <string, unknown> | undefined = undefined>(status : number,data :T ):ActionFailure <T >;
isHttpErrorpermalink
Checks whether this is an error thrown by error
.
ts
functionisHttpError <T extends number>(e : unknown,status ?:T | undefined):e isHttpError_1 & {status :T extends undefined ? never :T ;};
isRedirectpermalink
Checks whether this is a redirect thrown by redirect
.
ts
functionisRedirect (e : unknown):e isRedirect_1 ;
jsonpermalink
Crée un objet Response
en JSON à partir des données fournies.
ts
functionjson (data : any,init ?:ResponseInit | undefined):Response ;
redirectpermalink
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
functionredirect (status :| 300| 301| 302| 303| 304| 305| 306| 307| 308| ({} & number),location : string |URL ): never;
textpermalink
Crée un objet Response
à partir du body fournit.
ts
functiontext (body : string,init ?:ResponseInit | undefined):Response ;
@sveltejs/kit/hookspermalink
ts
import {sequence } from '@sveltejs/kit/hooks';
sequencepermalink
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éspreload
s'applique dans l'ordre normal, la première option "gagne" et aucune optionpreload
ne sera appelée après celle-cifilterSerializedResponseHeaders
fonctionne commepreload
ts
import {sequence } from '@sveltejs/kit/hooks';/// type: import('@sveltejs/kit').HandleBinding element 'html' implicitly has an 'any' type.7031Binding element 'html' implicitly has an 'any' type.async functionfirst ({event ,resolve }) {console .log ('first pre-processing');constresult = awaitresolve (event , {transformPageChunk : ({html }) => {// les transformations sont appliquées dans l'ordre inverseconsole .log ('first transform');returnhtml ;},preload : () => {// cette option gagne puisque c'est la première définie dans la chaîneconsole .log ('first preload');}});console .log ('first post-processing');returnBinding element 'event' implicitly has an 'any' type.Binding element 'resolve' implicitly has an 'any' type.7031result ;
7031Binding element 'event' implicitly has an 'any' type.Binding element 'resolve' implicitly has an 'any' type.}/// type: import('@sveltejs/kit').HandleBinding element 'html' implicitly has an 'any' type.7031Binding element 'html' implicitly has an 'any' type.async functionsecond ({event ,resolve }) {console .log ('second pre-processing');constresult = awaitresolve (event , {transformPageChunk : ({html }) => {console .log ('second transform');returnhtml ;},preload : () => {console .log ('second préchargement');},filterSerializedResponseHeaders : () => {// cette option gagne puisque c'est la première définie dans la chaîneconsole .log ('second filterSerializedResponseHeaders');}});console .log ('second post-processing');returnresult ;}export consthandle =sequence (first ,second );
ts
import {sequence } from '@sveltejs/kit/hooks';/// type: import('@sveltejs/kit').HandleBinding element 'html' implicitly has an 'any' type.7031Binding element 'html' implicitly has an 'any' type.async functionfirst ({event ,resolve }) {console .log ('first pre-processing');constresult = awaitresolve (event , {transformPageChunk : ({html }) => {// les transformations sont appliquées dans l'ordre inverseconsole .log ('first transform');returnhtml ;},preload : () => {// cette option gagne puisque c'est la première définie dans la chaîneconsole .log ('first preload');},});console .log ('first post-processing');returnBinding element 'event' implicitly has an 'any' type.Binding element 'resolve' implicitly has an 'any' type.7031result ;
7031Binding element 'event' implicitly has an 'any' type.Binding element 'resolve' implicitly has an 'any' type.}/// type: import('@sveltejs/kit').HandleBinding element 'html' implicitly has an 'any' type.7031Binding element 'html' implicitly has an 'any' type.async functionsecond ({event ,resolve }) {console .log ('second pre-processing');constresult = awaitresolve (event , {transformPageChunk : ({html }) => {console .log ('second transform');returnhtml ;},preload : () => {console .log ('second préchargement');},filterSerializedResponseHeaders : () => {// cette option gagne puisque c'est la première définie dans la chaîneconsole .log ('second filterSerializedResponseHeaders');},});console .log ('second post-processing');returnresult ;}export consthandle =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
functionsequence (...handlers : import('@sveltejs/kit').Handle []): import('@sveltejs/kit').Handle ;
@sveltejs/kit/nodepermalink
ts
import {createReadableStream ,getRequest ,setResponse } from '@sveltejs/kit/node';
createReadableStreampermalink
Converts a file on disk to a readable stream
ts
functioncreateReadableStream (file : string):ReadableStream ;
getRequestpermalink
ts
functiongetRequest ({request ,base ,bodySizeLimit }: {request : import('http').IncomingMessage ;base : string;bodySizeLimit ?: number;}):Promise <Request >;
setResponsepermalink
ts
functionsetResponse (res : import('http').ServerResponse ,response :Response ):Promise <void>;
@sveltejs/kit/node/polyfillspermalink
ts
import {installPolyfills } from '@sveltejs/kit/node/polyfills';
installPolyfillspermalink
Rend ces APIs web disponibles en tant que variables globales :
crypto
File
ts
functioninstallPolyfills (): void;
@sveltejs/kit/vitepermalink
ts
import {sveltekit } from '@sveltejs/kit/vite';
sveltekitpermalink
Renvoie les plugins Vite de SvelteKit.
ts
functionsveltekit ():Promise <import('vite').Plugin []>;