類型
產生的類型
RequestHandler
和 Load
類型都接受 Params
引數,讓您可以為 params
物件輸入類型。例如,此端點預期會有 foo
、bar
和 baz
參數
/** @type {import('@sveltejs/kit').RequestHandler<{
foo: string;
bar: string;
baz: string
}>} */
export async function function GET({ params }: {
params: any;
}): Promise<void>
GET({ params: any
params }) {
// ...
}
import type { type RequestHandler<Params extends Partial<Record<string, string>> = Partial<Record<string, string>>, RouteId extends string | null = string | null> = (event: RequestEvent<Params, RouteId>) => MaybePromise<Response>
A (event: RequestEvent) => Response
function exported from a +server.js
file that corresponds to an HTTP verb (GET
, PUT
, PATCH
, etc) and handles requests with that method.
It receives Params
as the first generic argument, which you can skip by using generated types instead.
RequestHandler } from '@sveltejs/kit';
export const const GET: RequestHandler<{
foo: string;
bar: string;
baz: string;
}>
GET: type RequestHandler<Params extends Partial<Record<string, string>> = Partial<Record<string, string>>, RouteId extends string | null = string | null> = (event: RequestEvent<Params, RouteId>) => MaybePromise<Response>
A (event: RequestEvent) => Response
function exported from a +server.js
file that corresponds to an HTTP verb (GET
, PUT
, PATCH
, etc) and handles requests with that method.
It receives Params
as the first generic argument, which you can skip by using generated types instead.
RequestHandler<{
foo: string
foo: string;
bar: string
bar: string;
baz: string
baz: string
}> = async ({ params: {
foo: string;
bar: string;
baz: string;
}
The parameters of the current route - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params }) => {
// ...
};
不用說,這樣寫很麻煩,而且可移植性較差(如果您將 [foo]
目錄重新命名為 [qux]
,則該類型將不再反映實際情況)。
為了解決這個問題,SvelteKit 會為每個端點和頁面產生 .d.ts
檔案
import type * as module "@sveltejs/kit"
Kit from '@sveltejs/kit';
type type RouteParams = {
foo: string;
bar: string;
baz: string;
}
RouteParams = {
foo: string
foo: string;
bar: string
bar: string;
baz: string
baz: string;
};
export type type PageServerLoad = (event: Kit.ServerLoadEvent<RouteParams, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageServerLoad = module "@sveltejs/kit"
Kit.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 = void | Record<...>, RouteId extends string | null = string | null> = (event: Kit.ServerLoadEvent<Params, ParentData, RouteId>) => MaybePromise<OutputData>
The generic form of PageServerLoad
and LayoutServerLoad
. You should import those from ./$types
(see generated types)
rather than using ServerLoad
directly.
ServerLoad<type RouteParams = {
foo: string;
bar: string;
baz: string;
}
RouteParams>;
export type type PageLoad = (event: Kit.LoadEvent<RouteParams, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageLoad = module "@sveltejs/kit"
Kit.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<...>, OutputData extends Record<string, unknown> | void = void | Record<...>, RouteId extends string | null = string | null> = (event: Kit.LoadEvent<Params, InputData, ParentData, RouteId>) => MaybePromise<OutputData>
The generic form of PageLoad
and LayoutLoad
. You should import those from ./$types
(see generated types)
rather than using Load
directly.
Load<type RouteParams = {
foo: string;
bar: string;
baz: string;
}
RouteParams>;
由於 TypeScript 配置中的 rootDirs
選項,這些檔案可以作為同層級檔案匯入您的端點和頁面
/** @type {import('./$types').PageServerLoad} */
export async function function GET(event: ServerLoadEvent<RouteParams, Record<string, any>, string | null>): MaybePromise<void | Record<string, any>>
GET({ params: RouteParams
The parameters of the current route - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params }) {
// ...
}
import type { type PageServerLoad = (event: ServerLoadEvent<RouteParams, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageServerLoad } from './$types';
export const const GET: PageServerLoad
GET: type PageServerLoad = (event: ServerLoadEvent<RouteParams, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageServerLoad = async ({ params: RouteParams
The parameters of the current route - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params }) => {
// ...
};
/** @type {import('./$types').PageLoad} */
export async function function load(event: LoadEvent<RouteParams, Record<string, any> | null, Record<string, any>, string | null>): MaybePromise<void | Record<string, any>>
load({ params: RouteParams
The parameters of the current page - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params, fetch: {
(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response>;
}
fetch
is equivalent to the native fetch
web API, with a few additional features:
- It can be used to make credentialed requests on the server, as it inherits the
cookie
and authorization
headers for the page request.
- It can make relative requests on the server (ordinarily,
fetch
requires a URL with an origin when used in a server context).
- Internal requests (e.g. for
+server.js
routes) go directly to the handler function when running on the server, without the overhead of an HTTP call.
- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the
text
and json
methods of the Response
object. Note that headers will not be serialized, unless explicitly included via filterSerializedResponseHeaders
- During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
You can learn more about making credentialed requests with cookies here
fetch }) {
// ...
}
import type { type PageLoad = (event: LoadEvent<RouteParams, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageLoad } from './$types';
export const const load: PageLoad
load: type PageLoad = (event: LoadEvent<RouteParams, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageLoad = async ({ params: RouteParams
The parameters of the current page - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params, fetch: {
(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response>;
}
fetch
is equivalent to the native fetch
web API, with a few additional features:
- It can be used to make credentialed requests on the server, as it inherits the
cookie
and authorization
headers for the page request.
- It can make relative requests on the server (ordinarily,
fetch
requires a URL with an origin when used in a server context).
- Internal requests (e.g. for
+server.js
routes) go directly to the handler function when running on the server, without the overhead of an HTTP call.
- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the
text
and json
methods of the Response
object. Note that headers will not be serialized, unless explicitly included via filterSerializedResponseHeaders
- During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
You can learn more about making credentialed requests with cookies here
fetch }) => {
// ...
};
為了使其運作,您自己的
tsconfig.json
或jsconfig.json
應從產生的.svelte-kit/tsconfig.json
擴展(其中.svelte-kit
是您的outDir
)
{ "extends": "./.svelte-kit/tsconfig.json" }
預設 tsconfig.json
產生的 .svelte-kit/tsconfig.json
檔案包含多種選項。有些是根據您的專案配置以程式方式產生,通常不應在沒有充分理由的情況下覆寫
{
"compilerOptions": {
"baseUrl": "..",
"paths": {
"$lib": "src/lib",
"$lib/*": "src/lib/*"
},
"rootDirs": ["..", "./types"]
},
"include": ["../src/**/*.js", "../src/**/*.ts", "../src/**/*.svelte"],
"exclude": ["../node_modules/**", "./**"]
}
其他選項是 SvelteKit 正常運作所必需的,除非您知道自己在做什麼,否則也不應更動
{
"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"
}
}
$lib
這是 src/lib
的簡單別名,或是指定為 config.kit.files.lib
的任何目錄。它允許您存取通用元件和實用模組,而無需 ../../../../
的繁瑣路徑。
$lib/server
$lib
的子目錄。SvelteKit 會阻止您將 $lib/server
中的任何模組匯入客戶端程式碼。請參閱僅限伺服器模組。
app.d.ts
app.d.ts
檔案是您應用程式的環境類型所在地,也就是說,這些類型無需明確匯入即可使用。
此檔案中始終包含 App
命名空間。此命名空間包含影響您互動的某些 SvelteKit 功能形狀的幾種類型。
錯誤
定義預期和非預期錯誤的通用形狀。預期錯誤是使用 error
函式拋出的。非預期錯誤由 handleError
鉤子處理,這些鉤子應返回此形狀。
interface Error {…}
message: string;
Locals
定義 event.locals
的介面,可以在伺服器 鉤子(handle
和 handleError
)、僅限伺服器的 load
函式和 +server.js
檔案中存取。
interface Locals {}
PageData
定義 $page.data 儲存的通用形狀,也就是在所有頁面之間共用的資料。./$types
中的 Load
和 ServerLoad
函式將會相應地縮小範圍。對於僅在特定頁面上存在的資料,請使用可選屬性。請勿新增索引簽名 ([key: string]: any
)。
interface PageData {}
PageState
$page.state
物件的形狀,可以使用 $app/navigation
中的 pushState
和 replaceState
函式進行操作。
interface PageState {}
Platform
如果您的轉接器透過 event.platform
提供平台特定的內容,您可以在此處指定它。
interface Platform {}