Skip to main content

Reference

Types

Edit this page on GitHub

Public types

以下の型は @sveltejs/kit からインポートすることができます:

Action

+page.server.js にある export const actions = {..} の一部である form action メソッドの形です。 詳細は form actions をご参照ください。

ts
type Action<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
OutputData extends Record<string, any> | void = Record<
string,
any
> | void,
RouteId extends string | null = string | null
> = (
event: RequestEvent<Params, RouteId>
) => MaybePromise<OutputData>;

ActionFailure

ts
interface ActionFailure<
T extends Record<string, unknown> | undefined = undefined
> {}
ts
status: number;
ts
data: T;
ts
[uniqueSymbol]: true;

ActionResult

fetch を通じて form action を呼び出したとき、そのレスポンスはこれらのうちいずれかの形となります。

<form method="post" use:enhance={() => {
  return ({ result }) => {
		// result is of type ActionResult
  };
}}
ts
type ActionResult<
Success extends
| Record<string, unknown>
| undefined = Record<string, any>,
Failure extends
| Record<string, unknown>
| undefined = Record<string, any>
> =
| { type: 'success'; status: number; data?: Success }
| { type: 'failure'; status: number; data?: Failure }
| { type: 'redirect'; status: number; location: string }
| { type: 'error'; status?: number; error: any };

Actions

+page.server.js にある export const actions = {..} オブジェクトの形です。 詳細は form actions をご参照ください。

ts
type Actions<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
OutputData extends Record<string, any> | void = Record<
string,
any
> | void,
RouteId extends string | null = string | null
> = Record<string, Action<Params, OutputData, RouteId>>;

Adapter

Adapters は、本番向けビルドを、あなたが選んだプラットフォームにデプロイできる形式に変換する役割を担います。

ts
interface Adapter {}
ts
name: string;

adapter の名前です。ログに使用されます。通常はパッケージー名と同じものになります。

ts
adapt(builder: Builder): MaybePromise<void>;
  • builder SvelteKit が提供するオブジェクトで、アプリを対象の環境に合わせる(adapt)ためのメソッドが含まれています

SvelteKit がアプリをビルドしたあとにこの関数が呼ばれます。

ts
supports?: {}

Checks called during dev and build to determine whether specific features will work in production with this adapter

ts
read?: (details: { config: any; route: { id: string } }) => boolean;
  • config The merged route config

Test support for read from $app/server

ts
emulate?(): MaybePromise<Emulator>;

Creates an Emulator, which allows the adapter to influence the environment during dev, build and prerendering

AfterNavigate

afterNavigate コールバックに渡される引数です。

ts
interface AfterNavigate extends Omit<Navigation, 'type'> {}
ts
type: Exclude<NavigationType, 'leave'>;

ナビゲーションのタイプ:

  • enter: アプリがハイドレーションされた場合
  • form: ユーザーが <form> を送信した場合
  • link: リンクをクリックしてナビゲーションがトリガーされた場合
  • goto: goto(...) をコール、またはリダイレクトによってナビゲーションがトリガーされた場合
  • popstate: 戻る/進む によってナビゲーションがトリガーされた場合
ts
willUnload: false;

afterNavigate はナビゲーションの完了後に呼び出されるため、ページをアンロードするナビゲーションでは決して呼び出されません。

AwaitedActions

ts
type AwaitedActions<
T extends Record<string, (...args: any) => any>
> = OptionalUnion<
{
[Key in keyof T]: UnpackValidationError<
Awaited<ReturnType<T[Key]>>
>;
}[keyof T]
>;

BeforeNavigate

beforeNavigate コールバックに渡される引数です。

ts
interface BeforeNavigate extends Navigation {}
ts
cancel(): void;

ナビゲーションを開始しないようにするためには、これを呼び出してください。

Builder

このオブジェクトは adapter の adapt 関数に渡されます。 アプリを対象の環境に合わせる(adapt)のに役立つ様々なメソッドとプロパティが含まれています。

ts
interface Builder {}
ts
log: Logger;

メッセージをコンソールにプリントします。Vite の logLevelinfo でない限り、log.infolog.minor はサイレントです。

ts
rimraf(dir: string): void;

dir とそのコンテンツを全て削除します。

ts
mkdirp(dir: string): void;

dir とそれに必要な親ディレクトリを作成します。

ts
config: ValidatedConfig;

完全に解決(resolve)された svelte.config.js です。

ts
prerendered: Prerendered;

プリレンダリングされたページとアセット情報です (もしあれば)。

ts
routes: RouteDefinition[];

全てのルート (プリレンダリングされたものも含む) の配列です

ts
createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise<void>;
  • fn 一連のルート(routes)をエントリーポイントにまとめる関数
  • deprecated Use builder.routes instead

アプリの1つ以上のルート(routes)にマップする別の関数を作成します。

ts
findServerAssets(routes: RouteDefinition[]): string[];

Find all the assets imported by server files belonging to routes

ts
generateFallback(dest: string): Promise<void>;

静的な web サーバーが、マッチするルート(route)がない場合に使用するフォールバックページ(fallback page)を生成します。シングルページアプリにとって有用です。

ts
generateEnvModule(): void;

Generate a module exposing build-time environment variables as $env/dynamic/public.

ts
generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): string;
  • opts アプリのベースディレクトリに対する相対パスと、オプションで、生成される manifest の形式 (esm または cjs) を指定

SvelteKit サーバーを初期化するためのサーバーサイド manifest を生成します。

ts
getBuildDirectory(name: string): string;
  • name ファイルへのパスで、ビルドディレクトリに対して相対

outDir 内の name ディレクトリへのパス (例: /path/to/.svelte-kit/my-adapter) を解決します。

ts
getClientDirectory(): string;

クライアントサイドのアセット (static ディレクトリのコンテンツを含む) があるディレクトリへの完全に解決されたパスを取得します。

ts
getServerDirectory(): string;

サーバーサイドコードがあるディレクトリへの完全に解決されたパスを取得します。

ts
getAppPath(): string;

設定された base パスを含むアプリケーションパス (例: my-base-path/_app) を取得します。

ts
writeClient(dest: string): string[];
  • dest 書き込み先のフォルダ
  • returns dest に書き込まれたファイルの配列

クライアントのアセットを dest に書き込みます。

ts
writePrerendered(dest: string): string[];
  • dest 書き込み先のフォルダ
  • returns dest に書き込まれたファイルの配列

プリレンダリングされたファイルを dest に書き込みます。

ts
writeServer(dest: string): string[];
  • dest 書き込み先のフォルダ
  • returns dest に書き込まれたファイルの配列

サーバーサイドのコードを dest に書き込みます。

ts
copy(
from: string,
to: string,
opts?: {
filter?(basename: string): boolean;
replace?: Record<string, string>;
}
): string[];
  • from コピー元のファイルやディレクトリ
  • to コピー先のファイルやディレクトリ
  • opts.filter ファイルやディレクトリをコピーするかどうか判定するための関数
  • opts.replace 置換する文字列のマップ
  • returns コピーされたファイルの配列

ファイルやディレクトリをコピーします。

ts
compress(directory: string): Promise<void>;
  • directory 圧縮したいファイルを含むディレクトリ

必要に応じて、directory にあるファイルを gzip や brotli で圧縮します。.gz ファイルや .br ファイルはオリジナルと同じ場所に生成されます。

Config

ts
interface Config {}

See the configuration reference for details.

Cookies

ts
interface Cookies {}
ts
get(name: string, opts?: import('cookie').CookieParseOptions): string | undefined;
  • name cookie の名前
  • opts 直接 cookie.parse に渡されるオプション。ドキュメントはこちら

事前に cookies.set で設定された cookie や、またはリクエストヘッダーから cookie を取得します。

ts
getAll(opts?: import('cookie').CookieParseOptions): Array<{ name: string; value: string }>;
  • opts 直接 cookie.parse に直接渡されるオプションです。ドキュメントはこちら

事前に cookies.set で設定されたすべての cookie や、またはリクエストヘッダーからすべての cookie を取得します。

ts
set(
name: string,
value: string,
opts: import('cookie').CookieSerializeOptions & { path: string }
): void;
  • name the name of the cookie
  • value the cookie value
  • opts the options, passed directly to cookie.serialize. See documentation here

cookie を設定します。これはレスポンスに set-cookie ヘッダーを追加し、また、現在のリクエスト中に cookies.getcookies.getAll を通じてその cookie を利用可能にします。

httpOnlysecure オプションはデフォルトで true となっており (http://localhost の場合は例外として securefalse です)、クライアントサイドの JavaScript で cookie を読み取ったり、HTTP 上で送信したりしたい場合は、明示的に無効にする必要があります。sameSite オプションのデフォルトは lax です。

You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children

ts
delete(name: string, opts: import('cookie').CookieSerializeOptions & { path: string }): void;
  • name the name of the cookie
  • opts the options, passed directly to cookie.serialize. The path must match the path of the cookie you want to delete. See documentation here

値に空文字列(empty string)を設定したり、有効期限(expiry date)を過去に設定することで、cookie を削除します。

You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children

ts
serialize(
name: string,
value: string,
opts: import('cookie').CookieSerializeOptions & { path: string }
): string;
  • name cookie の名前
  • value cookie の値
  • opts 直接 cookie.serialize に渡されるオプション。ドキュメントはこちら

cookie の名前と値のペアを Set-Cookie ヘッダー文字列にシリアライズします。ただし、それをレスポンスに適用しないでください。

httpOnlysecure オプションはデフォルトで true となっており (http://localhost の場合は例外として securefalse です)、クライアントサイドの JavaScript で cookie を読み取ったり、HTTP 上で送信したりしたい場合は、明示的に無効にする必要があります。sameSite オプションのデフォルトは lax です。

You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children

Emulator

A collection of functions that influence the environment during dev, build and prerendering

ts
interface Emulator {}
ts
platform?(details: { config: any; prerender: PrerenderOption }): MaybePromise<App.Platform>;

A function that is called with the current route config and prerender option and returns an App.Platform object

Handle

handle hook は SvelteKit サーバーがリクエストを受け取るたびに実行され、 レスポンスを決定します。 リクエストを表す event オブジェクトと、resolve と呼ばれる、ルート(route)をレンダリングして Response を生成する関数を受け取ります。 これによってレスポンスヘッダーとボディを変更したり、SvelteKit を完全にバイパスすることができます (例えば、プログラムによるルート(routes)実装など)。

ts
type Handle = (input: {
event: RequestEvent;
resolve(
event: RequestEvent,
opts?: ResolveOptions
): MaybePromise<Response>;
}) => MaybePromise<Response>;

HandleClientError

クライアントサイドの handleError hook は、ナビゲーション中に予期せぬエラー(unexpected error)がスローされたときに実行されます。

もし予期せぬエラーが load かその後のレンダリング中にスローされた場合、この関数はその error と error と event を引数に取って呼び出されます。 この関数では決してエラーをスローしないようにしてください。

ts
type HandleClientError = (input: {
error: unknown;
event: NavigationEvent;
status: number;
message: string;
}) => MaybePromise<void | App.Error>;

HandleFetch

handleFetch hook によって、サーバーで(またはプリレンダリング中に)実行される load 関数の内側で実行される fetch リクエストを変更 (または置換) することができます

ts
type HandleFetch = (input: {
event: RequestEvent;
request: Request;
fetch: typeof fetch;
}) => MaybePromise<Response>;

HandleServerError

サーバーサイドの handleError hook は、リクエストの応答中に予期せぬエラー(unexpected error)がスローされたときに実行されます。

もし予期せぬエラーが load か レンダリング中にスローされた場合、この関数はその error と event を引数に取って呼び出されます。 この関数では決してエラーをスローしないようにしてください。

ts
type HandleServerError = (input: {
error: unknown;
event: RequestEvent;
status: number;
message: string;
}) => MaybePromise<void | App.Error>;

HttpError

error 関数が返すオブジェクトです。

ts
interface HttpError {}
ts
status: number;

HTTP ステータスコード、400-599 の範囲内。

ts
body: App.Error;

エラーのコンテンツ

KitConfig

ts
interface KitConfig {}

See the configuration reference for details.

LessThan

ts
type LessThan<
TNumber extends number,
TArray extends any[] = []
> = TNumber extends TArray['length']
? TArray[number]
: LessThan<TNumber, [...TArray, TArray['length']]>;

Load

PageLoadLayoutLoad のジェネリックなフォームです。Load を直接使用するのではなく、./$types (generated types 参照) から インポートしてください。

ts
type Load<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
InputData extends Record<string, unknown> | null = Record<
string,
any
> | null,
ParentData extends Record<string, unknown> = Record<
string,
any
>,
OutputData extends Record<
string,
unknown
> | void = Record<string, any> | void,
RouteId extends string | null = string | null
> = (
event: LoadEvent<Params, InputData, ParentData, RouteId>
) => MaybePromise<OutputData>;

LoadEvent

PageLoadEventLayoutLoadEvent のジェネリック型。LoadEvent を直接使用するのではなく、 ./$types (generated types 参照) をインポートしたほうが良いでしょう。

ts
interface LoadEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
Data extends Record<string, unknown> | null = Record<
string,
any
> | null,
ParentData extends Record<string, unknown> = Record<
string,
any
>,
RouteId extends string | null = string | null
> extends NavigationEvent<Params, RouteId> {}
ts
fetch: typeof fetch;

fetchネイティブの fetch web API と同等ですが、いくつか機能が追加されています:

  • ページリクエストの cookieauthorization ヘッダーを継承するため、サーバー上で認証情報付きのリクエストを行うのに使用することができます。
  • サーバー上で相対パスのリクエストを行うことができます (通常、fetch は、サーバーのコンテキストで使用する場合 origin 付きの URL が必要です)
  • サーバー上で実行されている場合、内部リクエスト (例えば +server.js ルート(routes)に対するリクエスト) は、直接ハンドラ関数を呼び出すので、HTTP を呼び出すオーバーヘッドがありません。
  • サーバーサイドレンダリングでは、レスポンスはキャプチャされ、Response オブジェクトの textjson メソッドにフックされ、レンダリングされる HTML にインライン化されます。ヘッダーは、filterSerializedResponseHeaders を介して明示的に含めない限り、シリアライズされないことにご注意ください。
  • ハイドレーションでは、レスポンスは HTML から読み取られるため、一貫性が保証され、追加のネットワークリクエストを防ぎます

cookie を使用して機密情報を含むリクエストについてより学ぶには、こちらをご覧ください

ts
data: Data;

ルート(route) の、+layout.server.js+page.server.js にあるサーバー load 関数から返されたデータがあれば、それが含まれます。

ts
setHeaders(headers: Record<string, string>): void;

レスポンスにヘッダーを設定する必要がある場合、このメソッドを使ってそれを実現することができます。これはページをキャッシュさせる場合に便利です。例えば:

src/routes/blog/+page.js
ts
export async function load({ fetch, setHeaders }) {
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
7031
7031
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
const url = `https://cms.example.com/articles.json`;
const response = await fetch(url);
setHeaders({
age: response.headers.get('age'),
'cache-control': response.headers.get('cache-control')
});
return response.json();
}
src/routes/blog/+page.ts
ts
export async function load({ fetch, setHeaders }) {
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
7031
7031
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
const url = `https://cms.example.com/articles.json`;
const response = await fetch(url);
setHeaders({
age: response.headers.get('age'),
'cache-control': response.headers.get('cache-control'),
});
return response.json();
}

同じヘッダーを複数回設定することは (たとえ別々の load 関数であっても) エラーとなります。指定したヘッダーを設定できるのは一度だけです。

set-cookie ヘッダーは、setHeaders では追加できません。代わりに、サーバー load 関数で cookies API を使用してください。

ブラウザで load 関数を実行している場合、setHeaders には何の効果もありません。

ts
parent(): Promise<ParentData>;

await parent() は、親の +layout.jsload 関数から data を返します。 +layout.js が存在しない場合は、暗黙的に ({ data }) => data 関数として扱われます。つまり、親の +layout.server.js ファイルから data を返したり転送します。

await parent() を使用する場合、偶発的なウォーターフォールを引き起こさないようにご注意ください。例えば、親の data を戻り値にマージしたいだけであれば、他のデータを取得したあとにこれを呼び出すようにしてください。

ts
depends(...deps: Array<`${string}:${string}`>): void;

この関数は、load 関数が1つ以上の URL またはカスタムの識別子に依存していることを宣言します。この依存関係は、あとで invalidate()load を再実行させるのに使用されます。

fetch はあなたの代わりに depends を呼び出すので、ほとんどの場合これは必要ありません。必要になるのは、fetch をバイパスするカスタムの API クライアントを使用している場合のみです。

URL はロードされるページに対して絶対パスか相対パスで、エンコードされている必要があります。

カスタムの識別子は、URI 仕様 に準拠するため、1つ以上の小文字で始まり、それに続いてコロンを付ける必要があります。

以下の例では、depends を使用してカスタムの識別子を依存関係に登録する方法を示しています。これにより、ボタンがクリックされると invalidate が実行され、load 関数が再実行されます。

src/routes/+page.js
ts
let count = 0;
export async function load({ depends }) {
Binding element 'depends' implicitly has an 'any' type.7031Binding element 'depends' implicitly has an 'any' type.
depends('increase:count');
return { count: count++ };
}
src/routes/+page.ts
ts
let count = 0;
export async function load({ depends }) {
Binding element 'depends' implicitly has an 'any' type.7031Binding element 'depends' implicitly has an 'any' type.
depends('increase:count');
return { count: count++ };
}
src/routes/+page.svelte
<script>
	import { invalidate } from '$app/navigation';

	export let data;

	const increase = async () => {
		await invalidate('increase:count');
	}
</script>

<p>{data.count}<p>
<button on:click={increase}>Increase Count</button>
ts
untrack<T>(fn: () => T): T;

Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:

src/routes/+page.server.js
ts
export async function load({ untrack, url }) {
Binding element 'untrack' implicitly has an 'any' type.
Binding element 'url' implicitly has an 'any' type.
7031
7031
Binding element 'untrack' implicitly has an 'any' type.
Binding element 'url' implicitly has an 'any' type.
// Untrack url.pathname so that path changes don't trigger a rerun
if (untrack(() => url.pathname === '/')) {
return { message: 'Welcome!' };
}
}
src/routes/+page.server.ts
ts
export async function load({ untrack, url }) {
Binding element 'untrack' implicitly has an 'any' type.
Binding element 'url' implicitly has an 'any' type.
7031
7031
Binding element 'untrack' implicitly has an 'any' type.
Binding element 'url' implicitly has an 'any' type.
// Untrack url.pathname so that path changes don't trigger a rerun
if (untrack(() => url.pathname === '/')) {
return { message: 'Welcome!' };
}
}

LoadProperties

ts
type LoadProperties<
input extends Record<string, any> | void
> = input extends void
? undefined // needs to be undefined, because void will break intellisense
: input extends Record<string, any>
? input
: unknown;

Navigation

ts
interface Navigation {}
ts
from: NavigationTarget | null;

ナビゲーションがトリガーされた場所

ts
to: NavigationTarget | null;

ナビゲーションの行き先/行った先

ts
type: Exclude<NavigationType, 'enter'>;

The type of navigation:

  • form: The user submitted a <form>
  • leave: The app is being left either because the tab is being closed or a navigation to a different document is occurring
  • link: Navigation was triggered by a link click
  • goto: Navigation was triggered by a goto(...) call or a redirect
  • popstate: Navigation was triggered by back/forward navigation
ts
willUnload: boolean;

ナビゲーションの結果、ページがアンロードされるかどうか (すなわちクライアントサイドナビゲーションではない)

ts
delta?: number;

ヒストリーの 戻る/進む ナビゲーションの場合、戻る/進むのステップ数

ts
complete: Promise<void>;

A promise that resolves once the navigation is complete, and rejects if the navigation fails or is aborted. In the case of a willUnload navigation, the promise will never resolve

NavigationEvent

ts
interface NavigationEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
RouteId extends string | null = string | null
> {}
ts
params: Params;

現在のページのパラメータ - 例えば /blog/[slug] というルート(route)の場合は、{ slug: string } オブジェクト

ts
route: {}

現在のルート(route)に関する情報

ts
id: RouteId;

現在のルート(route)の ID - 例えば src/routes/blog/[slug] の場合は、/blog/[slug] となる

ts
url: URL;

現在のページの URL

NavigationTarget

特定のナビゲーションのターゲットに関する情報

ts
interface NavigationTarget {}
ts
params: Record<string, string> | null;

ターゲットページのパラメータ - 例えば /blog/[slug] というルート(route)の場合、{ slug: string } オブジェクト。 ターゲットが SvelteKit アプリではない場合 (ルート(route)として解決できない場合) は null となる。

ts
route: { id: string | null };

ターゲットのルート(route)に関する情報

ts
url: URL;

ナビゲーション先の URL

NavigationType

  • enter: アプリがハイドレーションされた場合
  • form: ユーザーが GET メソッドで <form> を送信した場合
  • leave: ユーザーがタブを閉じようとしたり 戻る/進む ボタンで違うドキュメントに行こうとしてアプリから離れようとした場合
  • link: リンクをクリックしてナビゲーションがトリガーされた場合
  • goto: goto(...) をコール、またはリダイレクトによってナビゲーションがトリガーされた場合
  • popstate: 戻る/進む によってナビゲーションがトリガーされた場合
ts
type NavigationType =
| 'enter'
| 'form'
| 'leave'
| 'link'
| 'goto'
| 'popstate';

NumericRange

ts
type NumericRange<
TStart extends number,
TEnd extends number
> = Exclude<TEnd | LessThan<TEnd>, LessThan<TStart>>;

OnNavigate

onNavigate コールバックに渡される引数です。

ts
interface OnNavigate extends Navigation {}
ts
type: Exclude<NavigationType, 'enter' | 'leave'>;

ナビゲーションのタイプ:

  • form: ユーザーが <form> を送信した場合
  • link: リンクがクリックされてナビゲーションがトリガーされた場合
  • goto: goto(...) をコール、またはリダイレクトによってナビゲーションがトリガーされた場合
  • popstate: 戻る/進む によってナビゲーションがトリガーされた場合
ts
willUnload: false;

onNavigate コールバックはクライアントサイドナビゲーションの直前に呼び出されるため、ページをアンロードするナビゲーションでは呼び出されません。

Page

$page store の形です

ts
interface Page<
Params extends Record<string, string> = Record<
string,
string
>,
RouteId extends string | null = string | null
> {}
ts
url: URL;

現在のページの URL

ts
params: Params;

現在のページのパラメータ - 例えば /blog/[slug] というルート(route)の場合は、{ slug: string } オブジェクト

ts
route: {}

現在のルート(route)に関する情報

ts
id: RouteId;

現在のルート(route)の ID - 例えば src/routes/blog/[slug] の場合、/blog/[slug] となる

ts
status: number;

現在のページの Http ステータスコード

ts
error: App.Error | null;

現在のページのエラーオブジェクト(存在する場合)。handleError hook から注入される。

ts
data: App.PageData & Record<string, any>;

現在のページにおいて、全ての load 関数からの全ての data がマージされた結果。共通の部分については App.PageData を通じて型付けできます。

ts
state: App.PageState;

The page state, which can be manipulated using the pushState and replaceState functions from $app/navigation.

ts
form: any;

Filled only after a form submission. See form actions for more info.

ParamMatcher

param matcher の形です。詳細については matching を参照。

ts
type ParamMatcher = (param: string) => boolean;

PrerenderOption

ts
type PrerenderOption = boolean | 'auto';

Redirect

redirect 関数が返すオブジェクトです。

ts
interface Redirect {}
ts
status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;

HTTP ステータスコード。300-308 の範囲内。

ts
location: string;

リダイレクト先のロケーション。

RequestEvent

ts
interface RequestEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
RouteId extends string | null = string | null
> {}
ts
cookies: Cookies;

現在のリクエストに関する cookie を取得または設定する

ts
fetch: typeof fetch;

fetchネイティブの fetch web API と同等ですが、いくつか機能が追加されています:

  • ページリクエストの cookieauthorization ヘッダーを継承するため、サーバー上で認証情報付きのリクエストを行うのに使用することができます。
  • サーバー上で相対パスのリクエストを行うことができます (通常、fetch は、サーバーのコンテキストで使用する場合 origin 付きの URL が必要です)
  • サーバー上で実行されている場合、内部リクエスト (例えば +server.js ルート(routes)に対するリクエスト) は、直接ハンドラ関数を呼び出すので、HTTP を呼び出すオーバーヘッドがありません。
  • サーバーサイドレンダリングでは、レスポンスはキャプチャされ、Response オブジェクトの textjson メソッドにフックされ、レンダリングされる HTML にインライン化されます。ヘッダーは、filterSerializedResponseHeaders を介して明示的に含めない限り、シリアライズされないことにご注意ください。
  • ハイドレーションでは、レスポンスは HTML から読み取られるため、一貫性が保証され、追加のネットワークリクエストを防ぎます

cookie を使用して機密情報を含むリクエストについてより学ぶには、こちらをご覧ください

ts
getClientAddress(): string;

クライアントの IP アドレスで、adapter によって設定される。

ts
locals: App.Locals;

handle hook 内でリクエストに追加されるカスタムの data が含まれる。

ts
params: Params;

現在のルート(route)のパラメータ - 例えば /blog/[slug] というルート(route)の場合は、{ slug: string } オブジェクト

ts
platform: Readonly<App.Platform> | undefined;

adapter を通じて利用可能になる追加の data。

ts
request: Request;

オリジナルのリクエストオブジェクト

ts
route: {}

現在のルート(route)に関する情報

ts
id: RouteId;

現在のルート(route)の ID - 例えば src/routes/blog/[slug] の場合、/blog/[slug] となる

ts
setHeaders(headers: Record<string, string>): void;

レスポンスにヘッダーを設定する必要がある場合、このメソッドを使ってそれを実現することができます。これはページをキャッシュさせる場合に便利です。例えば:

src/routes/blog/+page.js
ts
export async function load({ fetch, setHeaders }) {
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
7031
7031
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
const url = `https://cms.example.com/articles.json`;
const response = await fetch(url);
setHeaders({
age: response.headers.get('age'),
'cache-control': response.headers.get('cache-control')
});
return response.json();
}
src/routes/blog/+page.ts
ts
export async function load({ fetch, setHeaders }) {
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
7031
7031
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
const url = `https://cms.example.com/articles.json`;
const response = await fetch(url);
setHeaders({
age: response.headers.get('age'),
'cache-control': response.headers.get('cache-control'),
});
return response.json();
}

同じヘッダーを複数回設定することは (たとえ別々の load 関数であっても) エラーとなります。指定したヘッダーを設定できるのは一度だけです。

set-cookie ヘッダーは、setHeaders では追加できません。代わりに、cookies API を使用してください。

ts
url: URL;

リクエストされた URL。

ts
isDataRequest: boolean;

クライアントから +page/layout.server.js の data を要求するリクエストが来た場合は true となります。この場合、url プロパティからその data へのリクエストに関する内部情報が取り除かれます。 もしあなたにとってこの区別が重要な場合、このプロパティを使用してください。

ts
isSubRequest: boolean;

true for +server.js calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin fetch requests on the server.

RequestHandler

(event: RequestEvent) => Response という関数で、+server.js ファイルからエクスポートされます。HTTP verb (GET, PUT, PATCH, etc) に対応しており、それぞれの HTTP メソッドのリクエストを処理します。

1つめのジェネリックな引数(first generic argument)として Params を受け取りますが、代わりに generated types を使うことでこれをスキップすることができます。

ts
type RequestHandler<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
RouteId extends string | null = string | null
> = (
event: RequestEvent<Params, RouteId>
) => MaybePromise<Response>;

Reroute

The reroute hook allows you to modify the URL before it is used to determine which route to render.

ts
type Reroute = (event: { url: URL }) => void | string;

ResolveOptions

ts
interface ResolveOptions {}
ts
transformPageChunk?(input: { html: string; done: boolean }): MaybePromise<string | undefined>;
  • input html のチャンクとこれが最後のチャンクかどうかの情報

カスタムの変換を HTML に適用します。done が true である場合、それは最後のチャンクです。チャンクが整形された HTML であることは保証されませんが (例えば、要素の開始タグは含むが終了タグは含まれない、など)、 常に %sveltekit.head% やレイアウト(layout)/ページ(page)コンポーネントなどのような理にかなった境界 (sensible boundaries) で分割されます。

ts
filterSerializedResponseHeaders?(name: string, value: string): boolean;
  • name ヘッダーの名前
  • value ヘッダーの値

load 関数が fetch でリソースを読み込むときに、シリアライズされるレスポンスにどのヘッダーを含めるかを決定します。 デフォルトでは何も含まれません。

ts
preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean;
  • input ファイルのタイプとそのパス

<head> タグにどのファイルをプリロードの対象として追加するか決定します。 デフォルトでは、jscss ファイルがプリロードされます。

RouteDefinition

ts
interface RouteDefinition<Config = any> {}
ts
id: string;
ts
api: {
methods: Array<HttpMethod | '*'>;
};
ts
page: {
methods: Array<Extract<HttpMethod, 'GET' | 'POST'>>;
};
ts
pattern: RegExp;
ts
prerender: PrerenderOption;
ts
segments: RouteSegment[];
ts
methods: Array<HttpMethod | '*'>;
ts
config: Config;

SSRManifest

ts
interface SSRManifest {}
ts
appDir: string;
ts
appPath: string;
ts
assets: Set<string>;
ts
mimeTypes: Record<string, string>;
ts
_: {}

private fields

ts
client: NonNullable<BuildData['client']>;
ts
nodes: SSRNodeLoader[];
ts
routes: SSRRoute[];
ts
matchers(): Promise<Record<string, ParamMatcher>>;
ts
server_assets: Record<string, number>;

A [file]: size map of all assets imported by server code

Server

ts
class Server {}
ts
constructor(manifest: SSRManifest);
ts
init(options: ServerInitOptions): Promise<void>;
ts
respond(request: Request, options: RequestOptions): Promise<Response>;

ServerInitOptions

ts
interface ServerInitOptions {}
ts
env: Record<string, string>;

A map of environment variables

ts
read?: (file: string) => ReadableStream;

A function that turns an asset filename into a ReadableStream. Required for the read export from $app/server to work

ServerLoad

PageServerLoadLayoutServerLoad のジェネリックなフォームです。ServerLoad を直接使用するのではなく、./$types (generated types を参照) から インポートしてください。

ts
type ServerLoad<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
ParentData extends Record<string, any> = Record<
string,
any
>,
OutputData extends Record<string, any> | void = Record<
string,
any
> | void,
RouteId extends string | null = string | null
> = (
event: ServerLoadEvent<Params, ParentData, RouteId>
) => MaybePromise<OutputData>;

ServerLoadEvent

ts
interface ServerLoadEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
ParentData extends Record<string, any> = Record<
string,
any
>,
RouteId extends string | null = string | null
> extends RequestEvent<Params, RouteId> {}
ts
parent(): Promise<ParentData>;

await parent() は、親の +layout.server.jsload 関数から data を返します。

await parent() を使用する場合、偶発的なウォーターフォールを引き起こさないようにご注意ください。例えば、親の data を戻り値にマージしたいだけであれば、他のデータを取得したあとにこれを呼び出すようにしてください。

ts
depends(...deps: string[]): void;

この関数は、load 関数が1つ以上の URL またはカスタムの識別子に依存していることを宣言します。この依存関係は、あとで invalidate()load を再実行させるのに使用されます。

fetch はあなたの代わりに depends を呼び出すので、ほとんどの場合これは必要ありません。必要になるのは、fetch をバイパスするカスタムの API クライアントを使用している場合のみです。

URL はロードされるページに対して絶対パスか相対パスで、エンコードされている必要があります。

カスタムの識別子は、URI 仕様に準拠するため、1つ以上の小文字で始まり、それに続いてコロンを付ける必要があります。

以下の例では、depends を使用してカスタムの識別子を依存関係に登録する方法を示しています。これにより、ボタンがクリックされると invalidate が実行され、load 関数が再実行されます。

src/routes/+page.js
ts
let count = 0;
export async function load({ depends }) {
Binding element 'depends' implicitly has an 'any' type.7031Binding element 'depends' implicitly has an 'any' type.
depends('increase:count');
return { count: count++ };
}
src/routes/+page.ts
ts
let count = 0;
export async function load({ depends }) {
Binding element 'depends' implicitly has an 'any' type.7031Binding element 'depends' implicitly has an 'any' type.
depends('increase:count');
return { count: count++ };
}
src/routes/+page.svelte
<script>
	import { invalidate } from '$app/navigation';

	export let data;

	const increase = async () => {
		await invalidate('increase:count');
	}
</script>

<p>{data.count}<p>
<button on:click={increase}>Increase Count</button>
ts
untrack<T>(fn: () => T): T;

Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:

src/routes/+page.js
ts
export async function load({ untrack, url }) {
Binding element 'untrack' implicitly has an 'any' type.
Binding element 'url' implicitly has an 'any' type.
7031
7031
Binding element 'untrack' implicitly has an 'any' type.
Binding element 'url' implicitly has an 'any' type.
// Untrack url.pathname so that path changes don't trigger a rerun
if (untrack(() => url.pathname === '/')) {
return { message: 'Welcome!' };
}
}
src/routes/+page.ts
ts
export async function load({ untrack, url }) {
Binding element 'untrack' implicitly has an 'any' type.
Binding element 'url' implicitly has an 'any' type.
7031
7031
Binding element 'untrack' implicitly has an 'any' type.
Binding element 'url' implicitly has an 'any' type.
// Untrack url.pathname so that path changes don't trigger a rerun
if (untrack(() => url.pathname === '/')) {
return { message: 'Welcome!' };
}
}

Snapshot

The type of export const snapshot exported from a page or layout component.

ts
interface Snapshot<T = any> {}
ts
capture: () => T;
ts
restore: (snapshot: T) => void;

SubmitFunction

ts
type SubmitFunction<
Success extends
| Record<string, unknown>
| undefined = Record<string, any>,
Failure extends
| Record<string, unknown>
| undefined = Record<string, any>
> = (input: {
action: URL;
formData: FormData;
formElement: HTMLFormElement;
controller: AbortController;
submitter: HTMLElement | null;
cancel(): void;
}) => MaybePromise<
| void
| ((opts: {
formData: FormData;
formElement: HTMLFormElement;
action: URL;
result: ActionResult<Success, Failure>;
/**
* Call this to get the default behavior of a form submission response.
* @param options Set `reset: false` if you don't want the `<form>` values to be reset after a successful submission.
* @param invalidateAll Set `invalidateAll: false` if you don't want the action to call `invalidateAll` after submission.
*/
update(options?: {
reset?: boolean;
invalidateAll?: boolean;
}): Promise<void>;
}) => void)
>;

Private types

以下は上記の public types から参照されていますが、直接インポートすることはできません:

AdapterEntry

ts
interface AdapterEntry {}
ts
id: string;

HTTP サービス (例: serverless function) を一意に識別するための文字列で、重複を排除するために使用されます。 例えば、/foo/a-[b]/foo/[c] は別のルート(routes)ですが、 Netlify の _redirects ファイルではどちらも /foo/:param として表現されるので、ID を共有します

ts
filter(route: RouteDefinition): boolean;

候補のルート(route)と現在のルート(route)を比較し、 候補のルートを現在のルートのフォールバック(fallback)として扱うべきかどうかを判断する関数です。

Use cases:

  • Fallback pages: /foo/[c] is a fallback for /foo/a-[b], and /[...catchall] is a fallback for all routes
  • Grouping routes that share a common config: /foo should be deployed to the edge, /bar and /baz should be deployed to a serverless function
ts
complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise<void>;

エントリーが作成されると呼び出される関数です。 ここで、関数をファイルシステムに書き込み、リダイレクトマニフェストを生成します。

Csp

ts
namespace Csp {
type ActionSource = 'strict-dynamic' | 'report-sample';
type BaseSource =
| 'self'
| 'unsafe-eval'
| 'unsafe-hashes'
| 'unsafe-inline'
| 'wasm-unsafe-eval'
| 'none';
type CryptoSource = `${
| 'nonce'
| 'sha256'
| 'sha384'
| 'sha512'}-${string}`;
type FrameSource =
| HostSource
| SchemeSource
| 'self'
| 'none';
type HostNameScheme = `${string}.${string}` | 'localhost';
type HostSource =
`${HostProtocolSchemes}${HostNameScheme}${PortScheme}`;
type HostProtocolSchemes = `${string}://` | '';
type HttpDelineator = '/' | '?' | '#' | '\\';
type PortScheme = `:${number}` | '' | ':*';
type SchemeSource =
| 'http:'
| 'https:'
| 'data:'
| 'mediastream:'
| 'blob:'
| 'filesystem:';
type Source =
| HostSource
| SchemeSource
| CryptoSource
| BaseSource;
type Sources = Source[];
type UriPath = `${HttpDelineator}${string}`;
}

CspDirectives

ts
interface CspDirectives {}
ts
'child-src'?: Csp.Sources;
ts
'default-src'?: Array<Csp.Source | Csp.ActionSource>;
ts
'frame-src'?: Csp.Sources;
ts
'worker-src'?: Csp.Sources;
ts
'connect-src'?: Csp.Sources;
ts
'font-src'?: Csp.Sources;
ts
'img-src'?: Csp.Sources;
ts
'manifest-src'?: Csp.Sources;
ts
'media-src'?: Csp.Sources;
ts
'object-src'?: Csp.Sources;
ts
'prefetch-src'?: Csp.Sources;
ts
'script-src'?: Array<Csp.Source | Csp.ActionSource>;
ts
'script-src-elem'?: Csp.Sources;
ts
'script-src-attr'?: Csp.Sources;
ts
'style-src'?: Array<Csp.Source | Csp.ActionSource>;
ts
'style-src-elem'?: Csp.Sources;
ts
'style-src-attr'?: Csp.Sources;
ts
'base-uri'?: Array<Csp.Source | Csp.ActionSource>;
ts
sandbox?: Array<
| 'allow-downloads-without-user-activation'
| 'allow-forms'
| 'allow-modals'
| 'allow-orientation-lock'
| 'allow-pointer-lock'
| 'allow-popups'
| 'allow-popups-to-escape-sandbox'
| 'allow-presentation'
| 'allow-same-origin'
| 'allow-scripts'
| 'allow-storage-access-by-user-activation'
| 'allow-top-navigation'
| 'allow-top-navigation-by-user-activation'
>;
ts
'form-action'?: Array<Csp.Source | Csp.ActionSource>;
ts
'frame-ancestors'?: Array<Csp.HostSource | Csp.SchemeSource | Csp.FrameSource>;
ts
'navigate-to'?: Array<Csp.Source | Csp.ActionSource>;
ts
'report-uri'?: Csp.UriPath[];
ts
'report-to'?: string[];
ts
'require-trusted-types-for'?: Array<'script'>;
ts
'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>;
ts
'upgrade-insecure-requests'?: boolean;
ts
'require-sri-for'?: Array<'script' | 'style' | 'script style'>;
  • deprecated undefined
ts
'block-all-mixed-content'?: boolean;
  • deprecated undefined
ts
'plugin-types'?: Array<`${string}/${string}` | 'none'>;
  • deprecated undefined
ts
referrer?: Array<
| 'no-referrer'
| 'no-referrer-when-downgrade'
| 'origin'
| 'origin-when-cross-origin'
| 'same-origin'
| 'strict-origin'
| 'strict-origin-when-cross-origin'
| 'unsafe-url'
| 'none'
>;
  • deprecated undefined

HttpMethod

ts
type HttpMethod =
| 'GET'
| 'HEAD'
| 'POST'
| 'PUT'
| 'DELETE'
| 'PATCH'
| 'OPTIONS';

Logger

ts
interface Logger {}
ts
(msg: string): void;
ts
success(msg: string): void;
ts
error(msg: string): void;
ts
warn(msg: string): void;
ts
minor(msg: string): void;
ts
info(msg: string): void;

MaybePromise

ts
type MaybePromise<T> = T | Promise<T>;

PrerenderEntryGeneratorMismatchHandler

ts
interface PrerenderEntryGeneratorMismatchHandler {}
ts
(details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void;

PrerenderEntryGeneratorMismatchHandlerValue

ts
type PrerenderEntryGeneratorMismatchHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderEntryGeneratorMismatchHandler;

PrerenderHttpErrorHandler

ts
interface PrerenderHttpErrorHandler {}
ts
(details: {
status: number;
path: string;
referrer: string | null;
referenceType: 'linked' | 'fetched';
message: string;
}): void;

PrerenderHttpErrorHandlerValue

ts
type PrerenderHttpErrorHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderHttpErrorHandler;

PrerenderMap

ts
type PrerenderMap = Map<string, PrerenderOption>;

PrerenderMissingIdHandler

ts
interface PrerenderMissingIdHandler {}
ts
(details: { path: string; id: string; referrers: string[]; message: string }): void;

PrerenderMissingIdHandlerValue

ts
type PrerenderMissingIdHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderMissingIdHandler;

PrerenderOption

ts
type PrerenderOption = boolean | 'auto';

Prerendered

ts
interface Prerendered {}
ts
pages: Map<
string,
{
/** .html ファイルのロケーションで、output ディレクトリからの相対です */
file: string;
}
>;

path{ file } オブジェクトの map で、/foo という path に対応する foo.html/bar/ という path に対応する bar/index.html、となります。

ts
assets: Map<
string,
{
/** アセット(asset) の MIME type です */
type: string;
}
>;

path{ type } オブジェクトの map です。

ts
redirects: Map<
string,
{
status: number;
location: string;
}
>;

プリレンダリング中に発生したリダイレクトの map です。

ts
paths: string[];

プリレンダリングされた path の配列 (trailingSlash の設定に関わらず、末尾のスラッシュは取り除かれる)

RequestOptions

ts
interface RequestOptions {}
ts
getClientAddress(): string;
ts
platform?: App.Platform;

RouteSegment

ts
interface RouteSegment {}
ts
content: string;
ts
dynamic: boolean;
ts
rest: boolean;

TrailingSlash

ts
type TrailingSlash = 'never' | 'always' | 'ignore';

Generated types

RequestHandlerLoad の型はどちらも Params 引数を受け取りますが、その params オブジェクトに型を付けることができます。例えば、このエンドポイントは foobarbaz が渡されることを想定しています:

src/routes/[foo]/[bar]/[baz]/+page.server.js
ts
/** @type {import('@sveltejs/kit').RequestHandler<{
foo: string;
bar: string;
baz: string
}>} */
export async function GET({ params }) {
A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.2355A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.
// ...
}
src/routes/[foo]/[bar]/[baz]/+page.server.ts
ts
export const GET: import('@sveltejs/kit').RequestHandler<{
Type '({ params }: RequestEvent<{ foo: string; bar: string; baz: string; }, string | null>) => Promise<void>' is not assignable to type 'RequestHandler<{ foo: string; bar: string; baz: string; }, string | null>'. Type 'Promise<void>' is not assignable to type 'MaybePromise<Response>'. Type 'Promise<void>' is not assignable to type 'Promise<Response>'. Type 'void' is not assignable to type 'Response'.2322Type '({ params }: RequestEvent<{ foo: string; bar: string; baz: string; }, string | null>) => Promise<void>' is not assignable to type 'RequestHandler<{ foo: string; bar: string; baz: string; }, string | null>'. Type 'Promise<void>' is not assignable to type 'MaybePromise<Response>'. Type 'Promise<void>' is not assignable to type 'Promise<Response>'. Type 'void' is not assignable to type 'Response'.
foo: string;
bar: string;
baz: string;
}> = async ({ params }) => {
// ...
};

言うまでもなく、これを書くのは面倒で、移植性も低いです ([foo] ディレクトリを [qux] にリネームした場合、この型は実態を反映していないものとなります)。

この問題を解決するため、SvelteKit は各エンドポイント、各ページごとに .d.ts ファイルを生成します:

.svelte-kit/types/src/routes/[foo]/[bar]/[baz]/$types.d.ts
ts
import type * as Kit from '@sveltejs/kit';
type RouteParams = {
foo: string;
bar: string;
baz: string;
}
export type PageServerLoad = Kit.ServerLoad<RouteParams>;
export type PageLoad = Kit.Load<RouteParams>;

TypeScript の設定にある rootDirs オプションのおかげで、エンドポイントとページではこれらのファイルが同じディレクトリにあるかのようにインポートすることができます:

src/routes/[foo]/[bar]/[baz]/+page.server.js
ts
/** @type {import('./$types').PageServerLoad} */
export async function GET({ params }) {
// ...
}
src/routes/[foo]/[bar]/[baz]/+page.server.ts
ts
import type { PageServerLoad } from './$types';
export const GET: PageServerLoad = async ({ params }) => {
// ...
};
src/routes/[foo]/[bar]/[baz]/+page.js
ts
/** @type {import('./$types').PageLoad} */
export async function load({ params, fetch }) {
// ...
}
src/routes/[foo]/[bar]/[baz]/+page.ts
ts
import type { PageLoad } from './$types';
export const load: PageLoad = async ({ params, fetch }) => {
// ...
};

これを動作させるためには、tsconfig.json または jsconfig.json が生成された .svelte-kit/tsconfig.json を継承する必要があります (.svelte-kit の場所は outDir です):

{ "extends": "./.svelte-kit/tsconfig.json" }

Default tsconfig.json

生成された .svelte-kit/tsconfig.json ファイルには様々なオプションが含まれています。いくつかのオプションはプロジェクトの設定に基づいてプログラム的に生成されており、通常は、適切な理由なしに上書きするべきではありません。

.svelte-kit/tsconfig.json
ts
{
"compilerOptions": {
"baseUrl": "..",
"paths": {
"$lib": "src/lib",
"$lib/*": "src/lib/*"
},
"rootDirs": ["..", "./types"]
},
"include": ["../src/**/*.js", "../src/**/*.ts", "../src/**/*.svelte"],
"exclude": ["../node_modules/**", "./**"]
}

その他のオプションは SvelteKit が正常に動作するために必要なものであり、変更したときに何が起こるのか把握していないのであれば、そのままにしておく必要があります:

.svelte-kit/tsconfig.json
ts
{
"compilerOptions": {
// this ensures that types are explicitly
// imported with `import type`, which is
// necessary as svelte-preprocess cannot
// otherwise compile components correctly
"importsNotUsedAsValues": "error",
// Vite compiles one TypeScript module
// at a time, rather than compiling
// the entire module graph
"isolatedModules": true,
// TypeScript cannot 'see' when you
// use an imported value in your
// markup, so we need this
"preserveValueImports": true,
// This ensures both `vite build`
// and `svelte-package` work correctly
"lib": ["esnext", "DOM", "DOM.Iterable"],
"moduleResolution": "node",
"module": "esnext",
"target": "esnext"
}
}

App

Error

Defines the common shape of expected and unexpected errors. Expected errors are thrown using the error function. Unexpected errors are handled by the handleError hooks which should return this shape.

ts
interface Error {}
ts
message: string;

Locals

The interface that defines event.locals, which can be accessed in hooks (handle, and handleError), server-only load functions, and +server.js files.

ts
interface Locals {}

PageData

Defines the common shape of the $page.data store - that is, the data that is shared between all pages. The Load and ServerLoad functions in ./$types will be narrowed accordingly. Use optional properties for data that is only present on specific pages. Do not add an index signature ([key: string]: any).

ts
interface PageData {}

PageState

The shape of the $page.state object, which can be manipulated using the pushState and replaceState functions from $app/navigation.

ts
interface PageState {}

Platform

If your adapter provides platform-specific context via event.platform, you can specify it here.

ts
interface Platform {}