參考
類型
在 GitHub 上編輯此頁面公開類型永久連結
下列類型可以從 @sveltejs/kit
匯入
Action永久連結
export const actions = {..}
中表單動作方法的形狀,在 +page.server.js
中。更多資訊請參閱 表單動作。
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 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永久連結
export const actions = {..}
物件在 +page.server.js
中的形狀。更多資訊請參閱 表單動作。
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永久連結
適配器 負責取得製作版本並將其轉換成可部署至您選擇的平台的內容。
ts
interface Adapter {…}
ts
name: string;
適配器的名稱,用於記錄。通常會對應到套件名稱。
ts
adapt(builder: Builder): MaybePromise<void>;
builder
SvelteKit 提供的物件,其中包含適應應用程式的各種方法
此函式會在 SvelteKit 建置您的應用程式後呼叫。
ts
supports?: {…}
在開發和建置期間呼叫的檢查,用於確定特定功能是否會在生產環境中使用此轉接器。
ts
read?: (details: { config: any; route: { id: string } }) => boolean;
config
合併的路由設定檔
測試從 $app/server
讀取的支援
ts
emulate?(): MaybePromise<Emulator>;
建立一個 Emulator
,讓轉接器可以在開發、建置和預先渲染期間影響環境
AfterNavigatepermalink
傳遞給 afterNavigate
回呼的引數。
ts
interface AfterNavigate extends Omit<Navigation, 'type'> {…}
ts
type: Exclude<NavigationType, 'leave'>;
導覽的類型
enter
:應用程式已水化form
:使用者提交了<form>
link
:導覽是由連結點擊觸發的goto
:導覽是由goto(...)
呼叫或重新導向觸發的popstate
:導覽是由後退/前進導覽觸發的
ts
willUnload: false;
由於 afterNavigate
回呼是在導覽完成後呼叫的,因此它們永遠不會使用會卸載頁面的導覽呼叫。
AwaitedActionspermalink
ts
type AwaitedActions<T extends Record<string, (...args: any) => any>> = OptionalUnion<{[Key in keyof T]: UnpackValidationError<Awaited<ReturnType<T[Key]>>>;}[keyof T]>;
BeforeNavigatepermalink
傳遞給 beforeNavigate
回呼的引數。
ts
interface BeforeNavigate extends Navigation {…}
ts
cancel(): void;
呼叫此函式以防止導覽開始。
Builderpermalink
此物件傳遞給轉接器的 adapt
函式。它包含各種對調整應用程式有用的方法和屬性。
ts
interface Builder {…}
ts
log: Logger;
將訊息列印到主控台。除非 Vite 的 logLevel
為 info
,否則 log.info
和 log.minor
會保持靜默。
ts
rimraf(dir: string): void;
移除 dir
及其所有內容。
ts
mkdirp(dir: string): void;
建立 dir
和任何必要的父目錄。
ts
config: ValidatedConfig;
完全解析的 svelte.config.js
。
ts
prerendered: Prerendered;
預先渲染的頁面和資產(如果有)的資訊。
ts
routes: RouteDefinition[];
所有路由(包括預先渲染的)的陣列
ts
createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise<void>;
fn
將一組路由分組到一個進入點的函式- 已棄用 改用
builder.routes
建立個別的函式,對應到應用程式的一個或多個路由。
ts
findServerAssets(routes: RouteDefinition[]): string[];
找出屬於 routes
的伺服器檔案匯入的所有資產
ts
generateFallback(dest: string): Promise<void>;
為靜態 Web 伺服器產生一個備用頁面,供在沒有路由相符時使用。對單頁應用程式很有用。
ts
generateEnvModule(): void;
產生一個模組,將建置時間環境變數公開為 $env/dynamic/public
。
ts
generateManifest(opts: { relativePath: string; routes?: RouteDefinition[] }): string;
opts
應用程式基礎目錄的相對路徑,以及清單應產生之格式(esm 或 cjs)。
產生一個伺服器端清單,用於初始化 SvelteKit 伺服器。
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
目標資料夾- 傳回 寫入
dest
的檔案陣列
將客戶端資產寫入 dest
。
ts
writePrerendered(dest: string): string[];
dest
目標資料夾- 傳回 寫入
dest
的檔案陣列
將預先渲染的檔案寫入 dest
。
ts
writeServer(dest: string): string[];
dest
目標資料夾- 傳回 寫入
dest
的檔案陣列
將伺服器端程式碼寫入 dest
。
ts
copy(from: string,to: string,opts?: {filter?(basename: string): boolean;replace?: Record<string, string>;}): string[];
from
來源檔案或目錄to
目標檔案或目錄opts.filter
一個函式,用於判斷是否應複製檔案或目錄opts.replace
要取代的字串對應- 傳回 已複製的檔案陣列
複製檔案或目錄。
ts
compress(directory: string): Promise<void>;
directory
包含要壓縮檔案的目錄
在 directory
中壓縮檔案,使用 gzip 和 brotli(如果適用)。在原始檔案旁產生 .gz
和 .br
檔案。
設定永久連結
ts
interface Config {…}
請參閱 設定參考 以取得詳細資訊。
Cookie永久連結
ts
interface Cookies {…}
ts
get(name: string, opts?: import('cookie').CookieParseOptions): string | undefined;
name
Cookie 的名稱opts
選項,直接傳遞給cookie.parse
。請參閱 此處 的文件。
取得先前使用 cookies.set
設定或從請求標頭取得的 Cookie。
ts
getAll(opts?: import('cookie').CookieParseOptions): Array<{ name: string; value: string }>;
opts
選項,直接傳遞給cookie.parse
。請參閱 此處 的文件。
取得先前使用 cookies.set
設定或從請求標頭取得的所有 Cookie。
ts
set(name: string,value: string,opts: import('cookie').CookieSerializeOptions & { path: string }): void;
name
Cookie 的名稱value
Cookie 值opts
選項,直接傳遞給cookie.serialize
。請參閱 此處 的文件。
設定 Cookie。這會在回應中新增一個 set-cookie
標頭,但也會在當前請求期間透過 cookies.get
或 cookies.getAll
提供 Cookie。
httpOnly
和 secure
選項預設為 true
(除了在 https://127.0.0.1,其中 secure
為 false
),如果您希望 Cookie 可由客戶端 JavaScript 讀取和/或透過 HTTP 傳輸,則必須明確停用這些選項。sameSite
選項預設為 lax
。
您必須為 cookie 指定一個 path
。在大部分情況下,您應明確設定 path: '/'
,以讓 cookie 可用於您的整個應用程式。您可以使用相對路徑,或設定 path: ''
,以讓 cookie 僅在目前路徑及其子路徑上可用
ts
delete(name: string, opts: import('cookie').CookieSerializeOptions & { path: string }): void;
name
Cookie 的名稱opts
選項,直接傳遞給cookie.serialize
。path
必須與您要刪除的 cookie 路徑相符。請參閱文件 在此處
透過將其值設定為空字串,並將過期日期設定為過去,來刪除 cookie。
您必須為 cookie 指定一個 path
。在大部分情況下,您應明確設定 path: '/'
,以讓 cookie 可用於您的整個應用程式。您可以使用相對路徑,或設定 path: ''
,以讓 cookie 僅在目前路徑及其子路徑上可用
ts
serialize(name: string,value: string,opts: import('cookie').CookieSerializeOptions & { path: string }): string;
name
Cookie 的名稱value
Cookie 值opts
選項,直接傳遞給cookie.serialize
。請參閱 此處 的文件。
將 cookie 名稱-值對序列化為 Set-Cookie
標頭字串,但不要將其套用至回應。
httpOnly
和 secure
選項預設為 true
(除了在 https://127.0.0.1,其中 secure
為 false
),如果您希望 Cookie 可由客戶端 JavaScript 讀取和/或透過 HTTP 傳輸,則必須明確停用這些選項。sameSite
選項預設為 lax
。
您必須為 cookie 指定一個 path
。在大部分情況下,您應明確設定 path: '/'
,以讓 cookie 可用於您的整個應用程式。您可以使用相對路徑,或設定 path: ''
,以讓 cookie 僅在目前路徑及其子路徑上可用
模擬器永久連結
在開發、建置和預先渲染期間影響環境的函式集合
ts
interface Emulator {…}
ts
platform?(details: { config: any; prerender: PrerenderOption }): MaybePromise<App.Platform>;
會呼叫目前路由 config
和 prerender
選項的函式,並傳回 App.Platform
物件
處理永久連結
handle
勾子會在 SvelteKit 伺服器收到 要求 並決定 回應 時每次執行。它會收到代表要求的 event
物件,以及稱為 resolve
的函式,該函式會渲染路由並產生 Response
。這讓您可以修改回應標頭或本文,或完全繞過 SvelteKit(例如,用於以程式化方式實作路由)。
ts
type Handle = (input: {event: RequestEvent;resolve(event: RequestEvent,opts?: ResolveOptions): MaybePromise<Response>;}) => MaybePromise<Response>;
HandleClientError永久連結
當在導覽時發生意外錯誤時,會執行用戶端 handleError
勾子。
如果在載入或後續渲染期間發生意外錯誤,此函式會使用錯誤和事件呼叫。請確保此函式絕不會擲回錯誤。
ts
type HandleClientError = (input: {error: unknown;event: NavigationEvent;status: number;message: string;}) => MaybePromise<void | App.Error>;
HandleFetch永久連結
handleFetch
勾子讓您可以修改(或取代)在伺服器上(或預先渲染期間)執行的 load
函式內發生的 fetch
要求
ts
type HandleFetch = (input: {event: RequestEvent;request: Request;fetch: typeof fetch;}) => MaybePromise<Response>;
HandleServerError永久連結
當在回應要求時發生意外錯誤時,會執行伺服器端 handleError
勾子。
如果在載入或渲染期間發生意外的錯誤,此函式將會以錯誤和事件呼叫。請確保此函式絕不會擲出錯誤。
ts
type HandleServerError = (input: {error: unknown;event: RequestEvent;status: number;message: string;}) => MaybePromise<void | App.Error>;
HttpError永久連結
error
函式傳回的物件。
KitConfig永久連結
ts
interface KitConfig {…}
請參閱 設定參考 以取得詳細資訊。
LessThan永久連結
ts
type LessThan<TNumber extends number,TArray extends any[] = []> = TNumber extends TArray['length']? TArray[number]: LessThan<TNumber, [...TArray, TArray['length']]>;
Load永久連結
PageLoad
和 LayoutLoad
的一般形式。你應該從 ./$types
匯入這些(請參閱 已產生類型),而不是直接使用 Load
。
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永久連結
PageLoadEvent
和 LayoutLoadEvent
的一般形式。你應該從 ./$types
匯入這些(請參閱 已產生類型),而不是直接使用 LoadEvent
。
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
網路 API,具有一些額外功能
- 它可用於在伺服器上進行憑證請求,因為它繼承了頁面請求的
cookie
和authorization
標頭。 - 它可以在伺服器上進行相對請求(通常,
fetch
在伺服器環境中使用時需要具有來源的 URL)。 - 在伺服器上執行時,內部請求(例如
+server.js
路由)會直接傳遞到處理函式,而沒有 HTTP 呼叫的負擔。 - 在伺服器端渲染期間,回應將會被擷取並透過連接到
Response
物件的text
和json
方法內嵌到已渲染的 HTML 中。請注意,除非透過filterSerializedResponseHeaders
明確包含,否則標頭不會被序列化 - 在水化期間,回應將從 HTML 中讀取,保證一致性並防止額外的網路請求。
你可以在 這裡 進一步了解如何使用 cookie 進行憑證請求
ts
data: Data;
包含路由伺服器 load
函式 (在 +layout.server.js
或 +page.server.js
中) 傳回的資料 (如果有)。
ts
setHeaders(headers: Record<string, string>): void;
如果你需要為回應設定標頭,你可以使用此方法。這在你想讓頁面快取時很有用,例如
ts
export async functionBinding element 'fetch' implicitly has an 'any' type.load ({, fetch }) { setHeaders
Binding element 'setHeaders' implicitly has an 'any' type.7031
7031Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.consturl = `https://cms.example.com/articles.json`;constresponse = awaitfetch (url );setHeaders ({age :response .headers .get ('age'),'cache-control':response .headers .get ('cache-control')});returnresponse .json ();}
ts
export async functionBinding element 'fetch' implicitly has an 'any' type.load ({, fetch }) { setHeaders
Binding element 'setHeaders' implicitly has an 'any' type.7031
7031Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.consturl = `https://cms.example.com/articles.json`;constresponse = awaitfetch (url );setHeaders ({age :response .headers .get ('age'),'cache-control':response .headers .get ('cache-control'),});returnresponse .json ();}
多次設定同一個標頭 (即使在不同的 load
函式中) 是錯誤的 — 你只能設定一個給定的標頭一次。
你無法使用 setHeaders
新增 set-cookie
標頭 — 請改用僅伺服器的 load
函式中的 cookies
API。
當 load
函式在瀏覽器中執行時,setHeaders
沒有作用。
ts
parent(): Promise<ParentData>;
await parent()
從父層 +layout.js
load
函式傳回資料。隱含地,不存在的 +layout.js
會被視為 ({ data }) => data
函式,表示它會傳回並轉送來自父層 +layout.server.js
檔案的資料。
使用 await parent()
時,小心不要引發意外的瀑布效應。例如,如果你只想將父層資料合併到傳回的輸出中,請在擷取其他資料之後呼叫它。
ts
depends(...deps: Array<`${string}:${string}`>): void;
此函式宣告 load
函式對一個或多個 URL 或自訂識別碼有相依性,之後可以使用 invalidate()
來讓 load
重新執行。
大部分時間你不需要這個,因為 fetch
會代表你 depends
— 只有在你使用繞過 fetch
的自訂 API 程式時才需要。
URL 可以是絕對的或相對於正在載入的頁面,而且必須是 編碼 的。
自訂識別碼必須以一個或多個小寫字母開頭,後接一個冒號,以符合 URI 規格。
以下範例顯示如何使用 depends
來註冊對自訂識別碼的相依性,該識別碼會在按鈕按一下後被 invalidate
,讓 load
函式重新執行。
ts
letcount = 0;export async functionBinding element 'depends' implicitly has an 'any' type.7031Binding element 'depends' implicitly has an 'any' type.load ({}) { depends depends ('increase:count');return {count :count ++ };}
ts
letcount = 0;export async functionBinding element 'depends' implicitly has an 'any' type.7031Binding element 'depends' implicitly has an 'any' type.load ({}) { depends depends ('increase:count');return {count :count ++ };}
<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;
使用此函式來選擇退出對在回呼中同步呼叫的所有內容的相依性追蹤。範例
ts
export async functionBinding element 'untrack' implicitly has an 'any' type.load ({, untrack }) { url
Binding element 'url' implicitly has an 'any' type.7031
7031Binding 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 rerunif (untrack (() =>url .pathname === '/')) {return {message : 'Welcome!' };}}
ts
export async functionBinding element 'untrack' implicitly has an 'any' type.load ({, untrack }) { url
Binding element 'url' implicitly has an 'any' type.7031
7031Binding 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 rerunif (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'>;
導覽的類型
form
:使用者提交了<form>
leave
:應用程式因分頁關閉或導航至不同文件而離開link
:導覽是由連結點擊觸發的goto
:導覽是由goto(...)
呼叫或重新導向觸發的popstate
:導覽是由後退/前進導覽觸發的
ts
willUnload: boolean;
導航是否會導致頁面卸載(即非用戶端導航)
ts
delta?: number;
如果是瀏覽器返回/前進導航,則為返回/前進的步驟數
ts
complete: Promise<void>;
導航完成時會解析的 Promise,如果導航失敗或中止則會拒絕。如果是 willUnload
導航,則 Promise 永遠不會解析
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]
的路由,會是 { slug: string }
物件
ts
route: {…}
當前路由的資訊
ts
id: RouteId;
當前路由的 ID,例如對於 src/routes/blog/[slug]
,會是 /blog/[slug]
ts
url: URL;
當前頁面的 URL
NavigationTarget永久連結
特定導航目標的資訊。
ts
interface NavigationTarget {…}
ts
params: Record<string, string> | null;
目標頁面的參數,例如對於類似 /blog/[slug]
的路由,會是 { slug: string }
物件。如果目標不是 SvelteKit 應用程式的部分(無法解析為路由),則為 null
。
ts
route: { id: string | null };
目標路由的資訊
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
儲存的形狀
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]
的路由,會是 { slug: string }
物件
ts
route: {…}
當前路由的資訊
ts
id: RouteId;
當前路由的 ID,例如對於 src/routes/blog/[slug]
,會是 /blog/[slug]
ts
status: number;
當前頁面的 Http 狀態碼
ts
error: App.Error | null;
當前頁面的錯誤物件(如有)。從 handleError
鉤子填入。
ts
data: App.PageData & Record<string, any>;
當前頁面所有 load
函式的資料合併後的結果。您可以透過 App.PageData
輸入公分母。
ts
state: App.PageState;
頁面狀態,可以使用 $app/navigation
中的 pushState
和 replaceState
函式進行操作。
ts
form: any;
僅在提交表單後填入。有關更多資訊,請參閱 表單動作。
ParamMatcher永久連結
參數比對器的形狀。有關更多資訊,請參閱 比對。
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
網路 API,具有一些額外功能
- 它可用於在伺服器上進行憑證請求,因為它繼承了頁面請求的
cookie
和authorization
標頭。 - 它可以在伺服器上進行相對請求(通常,
fetch
在伺服器環境中使用時需要具有來源的 URL)。 - 在伺服器上執行時,內部請求(例如
+server.js
路由)會直接傳遞到處理函式,而沒有 HTTP 呼叫的負擔。 - 在伺服器端渲染期間,回應將會被擷取並透過連接到
Response
物件的text
和json
方法內嵌到已渲染的 HTML 中。請注意,除非透過filterSerializedResponseHeaders
明確包含,否則標頭不會被序列化 - 在水化期間,回應將從 HTML 中讀取,保證一致性並防止額外的網路請求。
你可以在 這裡 進一步了解如何使用 cookie 進行憑證請求
ts
getClientAddress(): string;
客戶端的 IP 位址,由轉接器設定。
ts
locals: App.Locals;
包含在 處理鉤子
中新增至要求的客製化資料。
ts
params: Params;
當前路由的參數 - 例如,對於像 /blog/[slug]
的路由,一個 { slug: string }
物件
ts
platform: Readonly<App.Platform> | undefined;
透過轉接器提供的其他資料。
ts
request: Request;
原始要求物件
ts
route: {…}
當前路由的資訊
ts
id: RouteId;
當前路由的 ID,例如對於 src/routes/blog/[slug]
,會是 /blog/[slug]
ts
setHeaders(headers: Record<string, string>): void;
如果你需要為回應設定標頭,你可以使用此方法。這在你想讓頁面快取時很有用,例如
ts
export async functionBinding element 'fetch' implicitly has an 'any' type.load ({, fetch }) { setHeaders
Binding element 'setHeaders' implicitly has an 'any' type.7031
7031Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.consturl = `https://cms.example.com/articles.json`;constresponse = awaitfetch (url );setHeaders ({age :response .headers .get ('age'),'cache-control':response .headers .get ('cache-control')});returnresponse .json ();}
ts
export async functionBinding element 'fetch' implicitly has an 'any' type.load ({, fetch }) { setHeaders
Binding element 'setHeaders' implicitly has an 'any' type.7031
7031Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.consturl = `https://cms.example.com/articles.json`;constresponse = awaitfetch (url );setHeaders ({age :response .headers .get ('age'),'cache-control':response .headers .get ('cache-control'),});returnresponse .json ();}
多次設定同一個標頭 (即使在不同的 load
函式中) 是錯誤的 — 你只能設定一個給定的標頭一次。
您無法使用 setHeaders
新增 set-cookie
標頭 - 請改用 cookies
API。
ts
url: URL;
要求的 URL。
ts
isDataRequest: boolean;
如果要求來自客戶端要求 +page/layout.server.js
資料,則為 true
。在此情況下,url
屬性會去除與資料要求相關的內部資訊。如果此區別對您很重要,請改用此屬性。
ts
isSubRequest: boolean;
對於來自 SvelteKit 的 +server.js
呼叫為 true
,而不會實際進行 HTTP 要求的負擔。當您在伺服器上進行同源 fetch
要求時,就會發生這種情況。
RequestHandler永久連結
一個從 +server.js
檔案導出的 (event: RequestEvent) => Response
函式,對應到一個 HTTP 動詞(GET
、PUT
、PATCH
等),並處理使用該方法的請求。
它接收 Params
作為第一個泛型引數,你可以使用 產生的型別 來跳過它。
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>;
Reroutepermalink
reroute
鉤子允許你在用來決定要呈現哪個路由之前修改 URL。
ts
type Reroute = (event: { url: URL }) => void | string;
ResolveOptionspermalink
ts
interface ResolveOptions {…}
ts
transformPageChunk?(input: { html: string; done: boolean }): MaybePromise<string | undefined>;
input
html 塊和這是否是最後一個塊的資訊
將自訂轉換套用至 HTML。如果 done
為 true,那就是最後一個塊。無法保證塊是格式良好的 HTML(例如,它們可能包含元素的開頭標籤,但不包含它的結尾標籤),但它們將始終在合理的分界處拆分,例如 %sveltekit.head%
或版面/頁面元件。
ts
filterSerializedResponseHeaders?(name: string, value: string): boolean;
name
標頭名稱value
標頭值
當 load
函式使用 fetch
載入資源時,決定哪些標頭應包含在序列化回應中。預設情況下,不會包含任何標頭。
ts
preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean;
input
檔案的類型和路徑
決定應新增什麼到 <head>
標籤中以預載入它。預設情況下,將預載入 js
和 css
檔案。
RouteDefinitionpermalink
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;
SSRManifestpermalink
ts
interface SSRManifest {…}
ts
appDir: string;
ts
appPath: string;
ts
assets: Set<string>;
ts
mimeTypes: Record<string, string>;
ts
_: {…}
私有欄位
ts
client: NonNullable<BuildData['client']>;
ts
nodes: SSRNodeLoader[];
ts
routes: SSRRoute[];
ts
matchers(): Promise<Record<string, ParamMatcher>>;
ts
server_assets: Record<string, number>;
伺服器程式碼匯入的所有資源的 [file]: size
映射
Serverpermalink
ts
class Server {…}
ts
constructor(manifest: SSRManifest);
ts
init(options: ServerInitOptions): Promise<void>;
ts
respond(request: Request, options: RequestOptions): Promise<Response>;
ServerInitOptionspermalink
ts
interface ServerInitOptions {…}
ts
env: Record<string, string>;
環境變數的映射
ts
read?: (file: string) => ReadableStream;
將資源檔名轉換為 ReadableStream
的函式。需要 $app/server
中的 read
匯出才能運作
ServerLoadpermalink
PageServerLoad
和 LayoutServerLoad
的一般形式。你應該從 ./$types
匯入它們(請參閱 產生的型別),而不是直接使用 ServerLoad
。
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>;
ServerLoadEventpermalink
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.js
load
函式的資料。
使用 await parent()
時,小心不要引發意外的瀑布效應。例如,如果你只想將父層資料合併到傳回的輸出中,請在擷取其他資料之後呼叫它。
ts
depends(...deps: string[]): void;
此函式宣告 load
函式對一個或多個 URL 或自訂識別碼有相依性,之後可以使用 invalidate()
來讓 load
重新執行。
大部分時間你不需要這個,因為 fetch
會代表你 depends
— 只有在你使用繞過 fetch
的自訂 API 程式時才需要。
URL 可以是絕對的或相對於正在載入的頁面,而且必須是 編碼 的。
自訂識別碼必須以一個或多個小寫字母開頭,後接一個冒號,以符合 URI 規格。
以下範例顯示如何使用 depends
來註冊對自訂識別碼的相依性,該識別碼會在按鈕按一下後被 invalidate
,讓 load
函式重新執行。
ts
letcount = 0;export async functionBinding element 'depends' implicitly has an 'any' type.7031Binding element 'depends' implicitly has an 'any' type.load ({}) { depends depends ('increase:count');return {count :count ++ };}
ts
letcount = 0;export async functionBinding element 'depends' implicitly has an 'any' type.7031Binding element 'depends' implicitly has an 'any' type.load ({}) { depends depends ('increase:count');return {count :count ++ };}
<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;
使用此函式來選擇退出對在回呼中同步呼叫的所有內容的相依性追蹤。範例
ts
export async functionBinding element 'untrack' implicitly has an 'any' type.load ({, untrack }) { url
Binding element 'url' implicitly has an 'any' type.7031
7031Binding 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 rerunif (untrack (() =>url .pathname === '/')) {return {message : 'Welcome!' };}}
ts
export async functionBinding element 'untrack' implicitly has an 'any' type.load ({, untrack }) { url
Binding element 'url' implicitly has an 'any' type.7031
7031Binding 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 rerunif (untrack (() =>url .pathname === '/')) {return {message : 'Welcome!' };}}
Snapshotpermalink
從頁面或版面元件匯出的 export const snapshot
的類型。
ts
interface Snapshot<T = any> {…}
ts
capture: () => T;
ts
restore: (snapshot: T) => void;
SubmitFunctionpermalink
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)>;
私有型別permalink
下列內容由上面記載的公開型別所參照,但無法直接匯入
AdapterEntry永久連結
ts
interface AdapterEntry {…}
ts
id: string;
一個字串,用於唯一識別 HTTP 服務(例如無伺服器函式),並用於重複資料刪除。例如,/foo/a-[b]
和 /foo/[c]
是不同的路由,但都會在 Netlify _redirects 檔案中表示為 /foo/:param
,因此它們共用一個 ID
ts
filter(route: RouteDefinition): boolean;
一個函式,用於比較候選路由與目前的路由,以確定是否應將其與目前的路由分組。
使用案例
- 備用頁面:
/foo/[c]
是/foo/a-[b]
的備用頁面,而/[...catchall]
是所有路由的備用頁面 - 分組共用相同
config
的路由:/foo
應部署到邊緣,/bar
和/baz
應部署到無伺服器函式
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[];}
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'?: string[];
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'>;
- 已棄用 未定義
ts
'block-all-mixed-content'?: boolean;
- 已棄用 未定義
ts
'plugin-types'?: Array<`${string}/${string}` | 'none'>;
- 已棄用 未定義
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'>;
- 已棄用 未定義
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,{/** The location of the .html file relative to the output directory */file: string;}>;
一個從 path
到 { file }
物件的對應,其中像 /foo
的路徑對應到 foo.html
,而像 /bar/
的路徑對應到 bar/index.html
。
ts
assets: Map<string,{/** The MIME type of the asset */type: string;}>;
一個從 path
到 { type }
物件的對應。
ts
redirects: Map<string,{status: number;location: string;}>;
一個在預先渲染期間遇到的重新導向的對應。
ts
paths: string[];
一個預先渲染的路徑陣列(不含尾隨斜線,不論 trailingSlash 組態為何)
RequestOptionspermalink
ts
interface RequestOptions {…}
ts
getClientAddress(): string;
ts
platform?: App.Platform;
RouteSegmentpermalink
ts
interface RouteSegment {…}
ts
content: string;
ts
dynamic: boolean;
ts
rest: boolean;
TrailingSlashpermalink
ts
type TrailingSlash = 'never' | 'always' | 'ignore';
產生的類型permalink
RequestHandler
和 Load
類型都接受一個 Params
參數,讓你為 params
物件指定類型。例如,這個端點預期 foo
、bar
和 baz
參數
ts
/** @type {import('@sveltejs/kit').RequestHandler<{foo: string;bar: string;baz: string}>} */export async functionA function whose declared type is neither 'void' nor 'any' must return a value.2355A function whose declared type is neither 'void' nor 'any' must return a value.({ GET params }) {// ...}
ts
export constType '({ 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'.: import('@sveltejs/kit'). GET RequestHandler <{foo : string;bar : string;baz : string;}> = async ({params }) => {// ...};
不用說,這樣寫很麻煩,而且可移植性較低(如果你將 [foo]
目錄重新命名為 [qux]
,類型就不再反映實際情況)。
為了解決這個問題,SvelteKit 會為你的每個端點和頁面產生 .d.ts
檔案
ts
import type * asKit from '@sveltejs/kit';typeRouteParams = {foo : string;bar : string;baz : string;}export typePageServerLoad =Kit .ServerLoad <RouteParams >;export typePageLoad =Kit .Load <RouteParams >;
這些檔案可以匯入到你的端點和頁面中作為兄弟元件,這要感謝 TypeScript 組態中的 rootDirs
選項
ts
/** @type {import('./$types').PageServerLoad} */export async functionGET ({params }) {// ...}
ts
import type {PageServerLoad } from './$types';export constGET :PageServerLoad = async ({params }) => {// ...};
ts
/** @type {import('./$types').PageLoad} */export async functionload ({params ,fetch }) {// ...}
ts
import type {PageLoad } from './$types';export constload :PageLoad = async ({params ,fetch }) => {// ...};
要讓這個運作,你自己的
tsconfig.json
或jsconfig.json
應該從產生的.svelte-kit/tsconfig.json
延伸(其中.svelte-kit
是你的outDir
)
{ "extends": "./.svelte-kit/tsconfig.json" }
預設的 tsconfig.jsonpermalink
產生的 .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 正常運作所必需的,除非你知道自己在做什麼,否則也應該保持不變
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"}}
Apppermalink
Errorpermalink
定義預期和意外錯誤的共用形狀。預期錯誤會使用 error
函式拋出。意外錯誤會由 handleError
鉤子處理,它應該回傳這個形狀。
ts
interface Error {…}
ts
message: string;
Localspermalink
定義 event.locals
的介面,可以在 鉤子(handle
和 handleError
)、僅限伺服器的 load
函式和 +server.js
檔案中存取。
ts
interface Locals {}
PageData永久連結
定義 $page.data 儲存 的常見形狀 - 也就是在所有頁面中共享的資料。Load
和 ServerLoad
函式在 ./$types
中會相應地縮小。對於僅存在於特定頁面的資料,請使用可選屬性。不要新增索引特徵 ([key: string]: any
)。
ts
interface PageData {}
PageState永久連結
$page.state
物件的形狀,可以使用 $app/navigation
中的 pushState
和 replaceState
函式來操作。
ts
interface PageState {}
Platform永久連結
如果您的轉接器透過 event.platform
提供 平台特定的內容,您可以在這裡指定它。
ts
interface Platform {}