跳至主要內容

@sveltejs/kit

import {
	class ServerServer,
	const VERSION: stringVERSION,
	function error(status: number, body: App.Error): never (+1 overload)

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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
error
,
function fail(status: number): ActionFailure<undefined> (+1 overload)

Create an ActionFailure object.

@paramstatus The HTTP status code. Must be in the range 400-599.
fail
,
function isActionFailure(e: unknown): e is ActionFailure<undefined>

Checks whether this is an action failure thrown by {@link fail } .

@parame The object to check.
isActionFailure
,
function isHttpError<T extends number>(e: unknown, status?: T | undefined): e is HttpError_1 & {
    status: T extends undefined ? never : T;
}

Checks whether this is an error thrown by {@link error } .

@paramstatus The status to filter for.
isHttpError
,
function isRedirect(e: unknown): e is Redirect_1

Checks whether this is a redirect thrown by {@link redirect } .

@parame The object to check.
isRedirect
,
function json(data: any, init?: ResponseInit | undefined): Response

Create a JSON Response object from the supplied data.

@paramdata The value that will be serialized as JSON.
@paraminit Options such as status and headers that will be added to the response. Content-Type: application/json and Content-Length headers will be added automatically.
json
,
function redirect(status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | ({} & number), location: string | URL): never

Redirect a request. When called during request handling, SvelteKit will return a redirect response. Make sure you’re not catching the thrown redirect, which would prevent SvelteKit from handling it.

@paramstatus The HTTP status code. Must be in the range 300-308.
@paramlocation The location to redirect to.
@throwsRedirect This error instructs SvelteKit to redirect to the specified location.
@throwsError If the provided status is invalid.
redirect
,
function text(body: string, init?: ResponseInit | undefined): Response

Create a Response object from the supplied body.

@parambody The value that will be used as-is.
@paraminit Options such as status and headers that will be added to the response. A Content-Length header will be added automatically.
text
} from '@sveltejs/kit';

伺服器

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

VERSION

const VERSION: string;

error

拋出一個帶有 HTTP 狀態碼和可選訊息的錯誤。當在請求處理期間呼叫時,這將導致 SvelteKit 返回錯誤響應,而不會調用 handleError。請確保您沒有捕獲拋出的錯誤,這會阻止 SvelteKit 處理它。

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

fail

建立一個 ActionFailure 物件。

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

isActionFailure

檢查這是否是由 fail 拋出的動作失敗。

function isActionFailure(e: unknown): e is ActionFailure;

isHttpError

檢查這是否是由 error 拋出的錯誤。

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

isRedirect

檢查這是否是由 redirect 拋出的重定向。

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

json

從提供的資料建立一個 JSON Response 物件。

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

redirect

重定向請求。當在請求處理期間呼叫時,SvelteKit 將返回重定向響應。請確保您沒有捕獲拋出的重定向,這會阻止 SvelteKit 處理它。

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

text

從提供的內容建立一個 Response 物件。

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

Action

表單操作方法的形狀,它是 +page.server.jsexport const actions = {..} 的一部分。有關更多資訊,請參閱表單操作

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

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

ActionResult

當通過 fetch 呼叫表單操作時,響應將是這些形狀之一。

<form method="post" use:enhance={() => {
	return ({ result }) => {
		// result is of type ActionResult
	};
}}
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.jsexport const actions = {..} 物件的形狀。有關更多資訊,請參閱表單操作

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

轉接器負責將生產版本轉換為可部署到您選擇的平台上的內容。

interface Adapter {}
name: string;

轉接器的名稱,用於記錄。通常會對應到套件名稱。

adapt(builder: Builder): MaybePromise<void>;
  • builder SvelteKit 提供的物件,其中包含用於調整應用程式的方法

在 SvelteKit 建置您的應用程式之後呼叫此函式。

supports?: {}

在開發和建置期間呼叫的檢查,以確定特定功能是否可以在生產環境中與此轉接器一起運作

read?: (details: { config: any; route: { id: string } }) => boolean;
  • config 合併後的路由組態

測試對來自 $app/serverread 的支援

emulate?(): MaybePromise<Emulator>;

建立一個 Emulator,允許轉接器在開發、建置和預先渲染期間影響環境

AfterNavigate

傳遞給 afterNavigate 回呼的引數。

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

導覽的類型

  • enter:應用程式已啟動
  • form:使用者提交了 <form>
  • link:導覽由連結點擊觸發
  • goto:導覽由 goto(...) 呼叫或重定向觸發
  • popstate:導覽由返回/向前導覽觸發
willUnload: false;

由於 afterNavigate 回呼是在導覽完成後呼叫的,因此它們永遠不會被呼叫到卸載頁面的導覽。

AwaitedActions

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

BeforeNavigate

傳遞給 beforeNavigate 回呼的引數。

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

呼叫此函式可防止導覽開始。

Builder

此物件會傳遞給轉接器的 adapt 函式。它包含各種對調整應用程式有用的方法和屬性。

interface Builder {}
log: Logger;

將訊息列印到主控台。除非 Vite 的 logLevelinfo,否則 log.infolog.minor 會保持靜默。

rimraf(dir: string): void;

移除 dir 及其所有內容。

mkdirp(dir: string): void;

建立 dir 和任何需要的父目錄。

config: ValidatedConfig;

完全解析的 svelte.config.js

prerendered: Prerendered;

有關預先渲染的頁面和資產的資訊(如果有的話)。

routes: RouteDefinition[];

所有路由的陣列(包括預先渲染的路由)

createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise<void>;
  • fn 將一組路由分組到進入點的函式
  • 已棄用 使用 builder.routes 來代替

建立對應到應用程式一或多個路由的個別函式。

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

尋找屬於 routes 的伺服器檔案匯入的所有資產

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

產生一個回退頁面,供靜態網站伺服器在沒有符合的路由時使用。這對於單頁應用程式很有用。

generateEnvModule(): void;

產生一個將建置時期的環境變數公開為 $env/dynamic/public 的模組。

generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): string;
  • opts 應用程式基本目錄的相對路徑,以及選擇性地應生成資訊清單的格式(esm 或 cjs)

產生一個伺服器端資訊清單,以使用 SvelteKit 伺服器初始化。

getBuildDirectory(name: string): string;
  • name 相對於建置目錄的檔案路徑

解析 outDirname 目錄的路徑,例如 /path/to/.svelte-kit/my-adapter

getClientDirectory(): string;

取得包含用戶端資產的目錄的完全解析路徑,包括 static 目錄的內容。

getServerDirectory(): string;

取得包含伺服器端程式碼的目錄的完全解析路徑。

getAppPath(): string;

取得應用程式路徑,包括任何已設定的 base 路徑,例如 my-base-path/_app

writeClient(dest: string): string[];
  • dest 目的地資料夾
  • 傳回 寫入 dest 的檔案陣列

將用戶端資產寫入 dest

writePrerendered(dest: string): string[];
  • dest 目的地資料夾
  • 傳回 寫入 dest 的檔案陣列

將預先渲染的檔案寫入 dest

writeServer(dest: string): string[];
  • dest 目的地資料夾
  • 傳回 寫入 dest 的檔案陣列

將伺服器端程式碼寫入 dest

copy(
	from: string,
	to: string,
	opts?: {
		filter?(basename: string): boolean;
		replace?: Record<string, string>;
	}
): string[];
  • from 來源檔案或目錄
  • to 目的地檔案或目錄
  • opts.filter 用於決定是否應複製檔案或目錄的函式
  • opts.replace 要替換的字串對應
  • 傳回 已複製的檔案陣列

複製檔案或目錄。

compress(directory: string): Promise<void>;
  • directory 包含要壓縮的檔案的目錄

使用 gzip 和 brotli 壓縮 directory 中的檔案(如適用)。在原始檔案旁生成 .gz.br 檔案。

Config

有關詳細資訊,請參閱組態參考

Cookies

interface Cookies {}
get(name: string, opts?: import('cookie').CookieParseOptions): string | undefined;
  • name Cookie 的名稱
  • opts 直接傳遞給 cookie.parse 的選項。請參閱 此處 的文件

取得先前使用 cookies.set 設定或從請求標頭取得的 Cookie。

getAll(opts?: import('cookie').CookieParseOptions): Array<{ name: string; value: string }>;
  • opts 直接傳遞給 cookie.parse 的選項。請參閱 此處 的文件

取得先前使用 cookies.set 設定或從請求標頭取得的所有 Cookie。

set(
	name: string,
	value: string,
	opts: import('cookie').CookieSerializeOptions & { path: string }
): void;
  • name Cookie 的名稱
  • value Cookie 值
  • opts 直接傳遞給 cookie.serialize 的選項。請參閱 此處 的文件

設定 Cookie。這會將 set-cookie 標頭新增至回應,但也會使 Cookie 在目前請求期間通過 cookies.getcookies.getAll 取得。

預設情況下,httpOnlysecure 選項為 true (除了 https://127.0.0.1,其 securefalse),如果希望 Cookie 可被用戶端 JavaScript 讀取或透過 HTTP 傳輸,則必須明確停用它們。sameSite 選項預設為 lax

您必須為 Cookie 指定一個 path。在大多數情況下,您應該明確設定 path: '/',以使 Cookie 在整個應用程式中都可用。您可以使用相對路徑,或設定 path: '' 使 Cookie 僅在目前路徑及其子路徑下可用。

delete(name: string, opts: import('cookie').CookieSerializeOptions & { path: string }): void;
  • name Cookie 的名稱
  • opts 為選項,直接傳遞給 cookie.serializepath 必須與您要刪除的 Cookie 路徑相符。請參閱此處的文件:here

透過將 Cookie 的值設定為空字串並將過期日期設定為過去來刪除 Cookie。

您必須為 Cookie 指定一個 path。在大多數情況下,您應該明確設定 path: '/',以使 Cookie 在整個應用程式中都可用。您可以使用相對路徑,或設定 path: '' 使 Cookie 僅在目前路徑及其子路徑下可用。

serialize(
	name: string,
	value: string,
	opts: import('cookie').CookieSerializeOptions & { path: string }
): string;
  • name Cookie 的名稱
  • value Cookie 值
  • opts 直接傳遞給 cookie.serialize 的選項。請參閱 此處 的文件

將 Cookie 名稱-值對序列化為 Set-Cookie 標頭字串,但不將其應用於回應。

預設情況下,httpOnlysecure 選項為 true (除了 https://127.0.0.1,其 securefalse),如果希望 Cookie 可被用戶端 JavaScript 讀取或透過 HTTP 傳輸,則必須明確停用它們。sameSite 選項預設為 lax

您必須為 Cookie 指定一個 path。在大多數情況下,您應該明確設定 path: '/',以使 Cookie 在整個應用程式中都可用。您可以使用相對路徑,或設定 path: '' 使 Cookie 僅在目前路徑及其子路徑下可用。

模擬器 (Emulator)

一組在開發、建置和預先渲染期間影響環境的函數。

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

一個函數,它會以目前的路由 configprerender 選項呼叫,並返回一個 App.Platform 物件。

處理 (Handle)

handle 鉤子會在 SvelteKit 伺服器每次收到 請求 時執行,並決定 回應。它接收一個代表請求的 event 物件和一個名為 resolve 的函數,該函數會渲染路由並產生一個 Response。這允許您修改回應標頭或主體,或完全繞過 SvelteKit (例如,用於以程式方式實作路由)。

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

處理用戶端錯誤 (HandleClientError)

當導覽時拋出意外錯誤時,會執行用戶端的 handleError 鉤子。

如果在載入或後續渲染期間拋出意外錯誤,則會使用錯誤和事件呼叫此函數。請確保此函數永遠不會拋出錯誤。

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

處理 Fetch (HandleFetch)

handleFetch 鉤子允許您修改(或替換)在伺服器上(或在預先渲染期間)執行的 load 函數內發生的 fetch 請求。

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

處理伺服器錯誤 (HandleServerError)

當回應請求時拋出意外錯誤時,會執行伺服器端的 handleError 鉤子。

如果在載入或渲染期間拋出意外錯誤,則會使用錯誤和事件呼叫此函數。請確保此函數永遠不會拋出錯誤。

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

HttpError

error 函數返回的物件。

interface HttpError {}
status: number;

HTTP 狀態碼,範圍為 400-599。

body: App.Error;

錯誤的內容。

KitConfig

有關詳細資訊,請參閱組態參考

小於 (LessThan)

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

載入 (Load)

PageLoadLayoutLoad 的通用形式。您應該從 ./$types 導入這些 (請參閱 產生的類型),而不是直接使用 Load

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 的通用形式。您應該從 ./$types 導入這些 (請參閱 產生的類型),而不是直接使用 LoadEvent

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> {}
fetch: typeof fetch;

fetch 等同於 原生 fetch Web API,但有一些額外功能

  • 它可以用於在伺服器上發出具有憑證的請求,因為它繼承了頁面請求的 cookieauthorization 標頭。
  • 它可以在伺服器上發出相對請求 (通常,在伺服器環境中使用時,fetch 需要一個帶有來源的 URL)。
  • 內部請求 (例如,用於 +server.js 路由) 在伺服器上執行時會直接轉到處理常式函數,而不會產生 HTTP 呼叫的額外負荷。
  • 在伺服器端渲染期間,回應將會被捕獲並透過掛鉤 Response 物件的 textjson 方法內嵌到渲染的 HTML 中。請注意,標頭將不會被序列化,除非透過 filterSerializedResponseHeaders 明確包含。
  • 在水合作用期間,回應將從 HTML 中讀取,保證一致性並防止額外的網路請求。

您可以在此處了解更多關於使用 Cookie 發出具有憑證的請求。

data: Data;

包含路由伺服器 load 函數 (在 +layout.server.js+page.server.js 中) 返回的資料,如果有的話。

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

如果您需要為回應設定標頭,可以使用此方法進行設定。例如,如果您希望快取頁面,這會很有用

src/routes/blog/+page
export async function 
function load({ fetch, setHeaders }: {
    fetch: any;
    setHeaders: any;
}): Promise<any>
load
({ fetch, setHeaders }) {
const const url: "https://cms.example.com/articles.json"url = `https://cms.example.com/articles.json`; const const response: anyresponse = await fetch: anyfetch(const url: "https://cms.example.com/articles.json"url); setHeaders: anysetHeaders({ age: anyage: const response: anyresponse.headers.get('age'), 'cache-control': const response: anyresponse.headers.get('cache-control') }); return const response: anyresponse.json(); }

多次設定相同的標頭 (即使在單獨的 load 函數中) 也是錯誤的 — 您只能設定給定標頭一次。

您無法使用 setHeaders 添加 set-cookie 標頭 — 請改為在僅伺服器的 load 函數中使用 cookies API。

load 函數在瀏覽器中執行時,setHeaders 無效。

parent(): Promise<ParentData>;

await parent() 返回來自父 +layout.js load 函數的資料。隱式地,遺失的 +layout.js 會被視為 ({ data }) => data 函數,這表示它會返回並轉發來自父 +layout.server.js 檔案的資料。

在使用 await parent() 時,請小心不要引入意外的瀑布。例如,如果您只想將父資料合併到返回的輸出中,請在提取其他資料之後呼叫它。

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

此函數宣告 load 函數依賴於一個或多個 URL 或自訂識別碼,這些識別碼隨後可與 invalidate() 一起使用,以導致 load 重新執行。

大多數時候您不需要此函數,因為 fetch 會代表您呼叫 depends — 只有當您使用繞過 fetch 的自訂 API 用戶端時才需要此函數。

URL 可以是絕對或相對於正在載入的頁面,並且必須是已編碼

自訂識別碼必須以一個或多個小寫字母,後接一個冒號開頭,以符合 URI 規格

以下範例顯示如何使用 depends 來註冊對自訂識別碼的依賴性,該識別碼會在按鈕點擊後被 invalidate,使 load 函數重新執行。

src/routes/+page
let let count: numbercount = 0;
export async function 
function load({ depends }: {
    depends: any;
}): Promise<{
    count: number;
}>
load
({ depends }) {
depends: anydepends('increase:count'); return { count: numbercount: let count: numbercount++ }; }
src/routes/+page
<script>
	import { invalidate } from '$app/navigation';

	let { data } = $props();

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

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

使用此函數可選擇退出回呼內同步呼叫的所有內容的依賴性追蹤。範例

src/routes/+page.server
export async function 
function load({ untrack, url }: {
    untrack: any;
    url: any;
}): Promise<{
    message: string;
} | undefined>
load
({ untrack, url }) {
// Untrack url.pathname so that path changes don't trigger a rerun if (untrack: anyuntrack(() => url: anyurl.pathname === '/')) { return { message: stringmessage: 'Welcome!' }; } }

載入屬性 (LoadProperties)

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;
interface Navigation {}
from: NavigationTarget | null;

導覽的觸發位置

to: NavigationTarget | null;

導覽將要/已前往的位置

type: Exclude<NavigationType, 'enter'>;

導覽的類型

  • form:使用者提交了 <form>
  • leave:正在離開應用程式,原因可能是分頁被關閉或正在發生導覽至不同的文件
  • link:導覽由連結點擊觸發
  • goto:導覽由 goto(...) 呼叫或重定向觸發
  • popstate:導覽由返回/向前導覽觸發
willUnload: boolean;

導覽是否會導致頁面被卸載 (即,不是用戶端導覽)

delta?: number;

在歷史記錄返回/前進導覽的情況下,返回/前進的步驟數

complete: Promise<void>;

一個 Promise,會在導覽完成後解析,如果導覽失敗或中止,則會拒絕。在 willUnload 導覽的情況下,Promise 永遠不會解析

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

目前頁面的參數 - 例如,對於像 /blog/[slug] 這樣的路由,會是一個 { slug: string } 物件

route: {}

有關目前路由的資訊

id: RouteId;

目前路由的 ID - 例如,對於 src/routes/blog/[slug],會是 /blog/[slug]

url: URL;

目前頁面的 URL

有關特定導覽目標的資訊。

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

目標頁面的參數 - 例如,對於像 /blog/[slug] 這樣的路由,會是一個 { slug: string } 物件。如果目標不是 SvelteKit 應用程式的一部分 (無法解析為路由),則為 null

route: { id: string | null };

有關目標路由的資訊

url: URL;

導覽到的 URL

  • enter:應用程式已啟動
  • form:使用者提交了具有 GET 方法的 <form>
  • leave:使用者正透過關閉分頁或使用返回/前進按鈕來前往不同的文件而離開應用程式
  • link:導覽由連結點擊觸發
  • goto:導覽由 goto(...) 呼叫或重定向觸發
  • popstate:導覽由返回/向前導覽觸發
type NavigationType =
	| 'enter'
	| 'form'
	| 'leave'
	| 'link'
	| 'goto'
	| 'popstate';

數值範圍 (NumericRange)

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

導覽時 (OnNavigate)

傳遞給 onNavigate 回呼的引數。

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

導覽的類型

  • form:使用者提交了 <form>
  • link:導覽由連結點擊觸發
  • goto:導覽由 goto(...) 呼叫或重定向觸發
  • popstate:導覽由返回/向前導覽觸發
willUnload: false;

由於 onNavigate 回呼會在用戶端導覽之前立即呼叫,因此它們永遠不會使用卸載頁面的導覽來呼叫。

頁面 (Page)

$page 儲存的形狀

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

目前頁面的 URL

params: Params;

目前頁面的參數 - 例如,對於像 /blog/[slug] 這樣的路由,會是一個 { slug: string } 物件

route: {}

有關目前路由的資訊

id: RouteId;

目前路由的 ID - 例如,對於 src/routes/blog/[slug],會是 /blog/[slug]

status: number;

目前頁面的 Http 狀態碼

error: App.Error | null;

目前頁面的錯誤物件 (如果有的話)。從 handleError 鉤子填寫。

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

目前頁面上所有 load 函數的所有資料合併結果。您可以使用 App.PageData 輸入通用分母。

state: App.PageState;

頁面狀態,可以使用 $app/navigationpushStatereplaceState 函數來操作。

form: any;

僅在提交表單後填寫。請參閱 表單動作 了解更多資訊。

參數匹配器 (ParamMatcher)

參數匹配器的形狀。請參閱 匹配 了解更多資訊。

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

預先渲染選項 (PrerenderOption)

type PrerenderOption = boolean | 'auto';

重新導向 (Redirect)

redirect 函數返回的物件

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

HTTP 狀態碼,範圍為 300-308。

location: string;

要重新導向到的位置。

請求事件 (RequestEvent)

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

取得或設定與目前請求相關的 Cookie

fetch: typeof fetch;

fetch 等同於 原生 fetch Web API,但有一些額外功能

  • 它可以用於在伺服器上發出具有憑證的請求,因為它繼承了頁面請求的 cookieauthorization 標頭。
  • 它可以在伺服器上發出相對請求 (通常,在伺服器環境中使用時,fetch 需要一個帶有來源的 URL)。
  • 內部請求 (例如,用於 +server.js 路由) 在伺服器上執行時會直接轉到處理常式函數,而不會產生 HTTP 呼叫的額外負荷。
  • 在伺服器端渲染期間,回應將會被捕獲並透過掛鉤 Response 物件的 textjson 方法內嵌到渲染的 HTML 中。請注意,標頭將不會被序列化,除非透過 filterSerializedResponseHeaders 明確包含。
  • 在水合作用期間,回應將從 HTML 中讀取,保證一致性並防止額外的網路請求。

您可以在此處了解更多關於使用 Cookie 發出具有憑證的請求。

getClientAddress(): string;

客戶端的 IP 位址,由介面卡設定。

locals: App.Locals;

包含在 伺服器 handle 鉤子 內新增至請求的自訂資料。

params: Params;

當前路由的參數 — 例如,對於像 /blog/[slug] 這樣的路由,會是一個 { slug: string } 物件

platform: Readonly<App.Platform> | undefined;

透過适配器提供的額外數據。

request: Request;

原始的請求物件

route: {}

有關目前路由的資訊

id: RouteId;

目前路由的 ID - 例如,對於 src/routes/blog/[slug],會是 /blog/[slug]

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

如果您需要為回應設定標頭,可以使用此方法進行設定。例如,如果您希望快取頁面,這會很有用

src/routes/blog/+page
export async function 
function load({ fetch, setHeaders }: {
    fetch: any;
    setHeaders: any;
}): Promise<any>
load
({ fetch, setHeaders }) {
const const url: "https://cms.example.com/articles.json"url = `https://cms.example.com/articles.json`; const const response: anyresponse = await fetch: anyfetch(const url: "https://cms.example.com/articles.json"url); setHeaders: anysetHeaders({ age: anyage: const response: anyresponse.headers.get('age'), 'cache-control': const response: anyresponse.headers.get('cache-control') }); return const response: anyresponse.json(); }

多次設定相同的標頭 (即使在單獨的 load 函數中) 也是錯誤的 — 您只能設定給定標頭一次。

您不能使用 setHeaders 添加 set-cookie 標頭 — 請改用 cookies API。

url: URL;

請求的 URL。

isDataRequest: boolean;

如果請求來自客戶端要求 +page/layout.server.js 數據,則為 true。在這種情況下,url 屬性將會被移除與數據請求相關的內部資訊。如果這個區別對您很重要,請改用此屬性。

isSubRequest: boolean;

對於來自 SvelteKit 的 +server.js 呼叫,且沒有實際發出 HTTP 請求的負擔時,則為 true。當您在伺服器上發出同源 fetch 請求時會發生這種情況。

RequestHandler

+server.js 檔案導出的 (event: RequestEvent) => Response 函數,它對應於一個 HTTP 動詞(GETPUTPATCH 等),並處理具有該方法的請求。

它接收 Params 作為第一個泛型參數,您可以透過使用產生的類型來跳過它。

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

reroute hook 允許您在 URL 被用來決定要渲染哪個路由之前修改它。

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

ResolveOptions

interface ResolveOptions {}
transformPageChunk?(input: { html: string; done: boolean }): MaybePromise<string | undefined>;
  • input HTML 片段以及是否為最後一個片段的資訊

將自定義轉換應用於 HTML。如果 done 為 true,則表示這是最後一個片段。無法保證片段是格式正確的 HTML(它們可能包含元素的開始標籤,但不包含結束標籤,例如),但它們總是會在合理的邊界處分割,例如 %sveltekit.head% 或 layout/page 元件。

filterSerializedResponseHeaders?(name: string, value: string): boolean;
  • name 標頭名稱
  • value 標頭值

決定當 load 函數使用 fetch 加載資源時,哪些標頭應該包含在序列化的響應中。預設情況下,不會包含任何標頭。

preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean;
  • input 檔案的類型及其路徑

決定應該將哪些內容添加到 <head> 標籤中以進行預載。預設情況下,jscss 檔案將會被預載。

RouteDefinition

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

SSRManifest

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

私有欄位

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

伺服器程式碼匯入的所有資源的 [file]: size 對應表

ServerInitOptions

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

環境變數的對應表

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

將資源檔名轉換為 ReadableStream 的函數。$app/server 中的 read 導出功能需要此項才能運作

ServerLoad

PageServerLoadLayoutServerLoad 的泛型形式。您應該從 ./$types 匯入它們(請參閱產生的類型),而不是直接使用 ServerLoad

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

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> {}
parent(): Promise<ParentData>;

await parent() 會從父層 +layout.server.jsload 函數返回資料。

在使用 await parent() 時,請小心不要引入意外的瀑布。例如,如果您只想將父資料合併到返回的輸出中,請在提取其他資料之後呼叫它。

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

此函數宣告 load 函數依賴於一個或多個 URL 或自訂識別碼,這些識別碼隨後可與 invalidate() 一起使用,以導致 load 重新執行。

大多數時候您不需要此函數,因為 fetch 會代表您呼叫 depends — 只有當您使用繞過 fetch 的自訂 API 用戶端時才需要此函數。

URL 可以是絕對或相對於正在載入的頁面,並且必須是已編碼

自訂識別碼必須以一個或多個小寫字母,後接一個冒號開頭,以符合 URI 規格

以下範例顯示如何使用 depends 來註冊對自訂識別碼的依賴性,該識別碼會在按鈕點擊後被 invalidate,使 load 函數重新執行。

src/routes/+page
let let count: numbercount = 0;
export async function 
function load({ depends }: {
    depends: any;
}): Promise<{
    count: number;
}>
load
({ depends }) {
depends: anydepends('increase:count'); return { count: numbercount: let count: numbercount++ }; }
src/routes/+page
<script>
	import { invalidate } from '$app/navigation';

	let { data } = $props();

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

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

使用此函數可選擇退出回呼內同步呼叫的所有內容的依賴性追蹤。範例

src/routes/+page
export async function 
function load({ untrack, url }: {
    untrack: any;
    url: any;
}): Promise<{
    message: string;
} | undefined>
load
({ untrack, url }) {
// Untrack url.pathname so that path changes don't trigger a rerun if (untrack: anyuntrack(() => url: anyurl.pathname === '/')) { return { message: stringmessage: 'Welcome!' }; } }

Snapshot

從頁面或版面配置元件導出的 export const snapshot 的類型。

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

SubmitFunction

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)
>;

私有類型

以下內容被上面文檔中公開的類型引用,但不能直接匯入

AdapterEntry

interface AdapterEntry {}
id: string;

一個唯一識別 HTTP 服務(例如,無伺服器函數)並用於去重複化的字串。例如,/foo/a-[b]/foo/[c] 是不同的路由,但都會在 Netlify 的 _redirects 檔案中表示為 /foo/:param,因此它們共用一個 ID

filter(route: RouteDefinition): boolean;

一個函數,將候選路由與當前路由進行比較,以確定是否應該將其與當前路由分組。

使用案例

  • 後備頁面:/foo/[c]/foo/a-[b] 的後備,而 /[...catchall] 是所有路由的後備
  • 將共用一個共同 config 的路由進行分組:/foo 應該部署到邊緣,/bar/baz 應該部署到無伺服器函數
complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise<void>;

一旦建立條目後被調用的函數。您應該在此處將函數寫入檔案系統並產生重定向清單。

Csp

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[];
}

CspDirectives

interface CspDirectives {}
'child-src'?: Csp.Sources;
'default-src'?: Array<Csp.Source | Csp.ActionSource>;
'frame-src'?: Csp.Sources;
'worker-src'?: Csp.Sources;
'connect-src'?: Csp.Sources;
'font-src'?: Csp.Sources;
'img-src'?: Csp.Sources;
'manifest-src'?: Csp.Sources;
'media-src'?: Csp.Sources;
'object-src'?: Csp.Sources;
'prefetch-src'?: Csp.Sources;
'script-src'?: Array<Csp.Source | Csp.ActionSource>;
'script-src-elem'?: Csp.Sources;
'script-src-attr'?: Csp.Sources;
'style-src'?: Array<Csp.Source | Csp.ActionSource>;
'style-src-elem'?: Csp.Sources;
'style-src-attr'?: Csp.Sources;
'base-uri'?: Array<Csp.Source | Csp.ActionSource>;
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'
>;
'form-action'?: Array<Csp.Source | Csp.ActionSource>;
'frame-ancestors'?: Array<Csp.HostSource | Csp.SchemeSource | Csp.FrameSource>;
'navigate-to'?: Array<Csp.Source | Csp.ActionSource>;
'report-uri'?: string[];
'report-to'?: string[];
'require-trusted-types-for'?: Array<'script'>;
'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>;
'upgrade-insecure-requests'?: boolean;
'require-sri-for'?: Array<'script' | 'style' | 'script style'>;
  • 已過時
'block-all-mixed-content'?: boolean;
  • 已過時
'plugin-types'?: Array<`${string}/${string}` | 'none'>;
  • 已過時
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'
>;
  • 已過時

HttpMethod

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

Logger

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

MaybePromise

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

PrerenderEntryGeneratorMismatchHandler

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

PrerenderEntryGeneratorMismatchHandlerValue

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

PrerenderHttpErrorHandler

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

PrerenderHttpErrorHandlerValue

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

PrerenderMap

type PrerenderMap = Map<string, PrerenderOption>;

PrerenderMissingIdHandler

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

PrerenderMissingIdHandlerValue

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

預先渲染選項 (PrerenderOption)

type PrerenderOption = boolean | 'auto';

Prerendered

interface Prerendered {}
pages: Map<
string,
{
	/** The location of the .html file relative to the output directory */
	file: string;
}
>;

path{ file } 物件的對應表,其中像 /foo 這樣的路徑對應於 foo.html,而像 /bar/ 這樣的路徑對應於 bar/index.html

assets: Map<
string,
{
	/** The MIME type of the asset */
	type: string;
}
>;

path{ type } 物件的對應表。

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

在預渲染期間遇到的重定向的對應表。

paths: string[];

預渲染路徑的陣列(不包含尾部斜線,無論 trailingSlash 配置如何)

RequestOptions

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

RouteSegment

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

TrailingSlash

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

在 GitHub 上編輯此頁面

上一個 下一個