Types
生成类型
请求处理器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: anyparams }) {
// ...
}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: stringfoo: string;
bar: stringbar: string;
baz: stringbaz: 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: stringfoo: string;
bar: stringbar: string;
baz: stringbaz: string;
};
export type type RequestHandler = (event: Kit.RequestEvent<RouteParams, string | null>) => MaybePromise<Response>RequestHandler = module "@sveltejs/kit"Kit.type RequestHandler<Params extends Partial<Record<string, string>> = Partial<Record<string, string>>, RouteId extends string | null = string | null> = (event: Kit.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<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').RequestHandler} */
export async function GET({ params: RouteParamsThe parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.
params }) {
// ...
}import type { type RequestHandler = (event: RequestEvent<RouteParams, string | null>) => MaybePromise<Response>RequestHandler } from './$types';
export const GET: type RequestHandler = (event: RequestEvent<RouteParams, string | null>) => MaybePromise<Response>RequestHandler = async ({ params: RouteParamsThe 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: RouteParamsThe 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: PageLoadload: type PageLoad = (event: LoadEvent<RouteParams, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>PageLoad = async ({ params: RouteParamsThe 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 }) => {
// ...
};返回类型通过 $types 模块分别作为 PageData 和 LayoutData 可用,而所有 Actions 返回值的并集则可用作 ActionData。
从版本 2.16.0 开始,提供了两种额外的辅助类型:`PageProps`定义了`data: PageData`,以及当定义了操作时,`form: ActionData`,而`LayoutProps`定义了`data: LayoutData`,以及`children: Snippet`。
<script>
/** @type {import('./$types').PageProps} */
let { data, form } = $props();
</script><script lang="ts">
import type { PageProps } from './$types';
let { data, form }: PageProps = $props();
</script>[!旧版] 在 2.16.0 之前:
src/routes/+page<script> /** @type {{ data: import('./$types').PageData, form: import('./$types').ActionData }} */ let { data, form } = $props(); </script><script lang="ts"> import type { PageData, ActionData } from './$types'; let { data, form }: { data: PageData, form: ActionData } = $props(); </script>使用 Svelte 4:
src/routes/+page<script> /** @type {import('./$types').PageData} */ export let data; /** @type {import('./$types').ActionData} */ export let form; </script><script lang="ts"> import type { PageData, ActionData } from './$types'; export let data: PageData; export let form: ActionData; </script>
[!注意] 要使此功能正常工作,您的自己的
tsconfig.json或jsconfig.json应从生成的.svelte-kit/tsconfig.json扩展(其中.svelte-kit是您的outDir):
{ "extends": "./.svelte-kit/tsconfig.json" }
默认 tsconfig.json
生成的 .svelte-kit/tsconfig.json 文件包含多种选项。其中一些是根据您的项目配置自动生成的,通常在没有充分理由的情况下不应更改:
{
"compilerOptions": {
"paths": {
"$lib": ["../src/lib"],
"$lib/*": ["../src/lib/*"]
},
"rootDirs": ["..", "./types"]
},
"include": [
"ambient.d.ts",
"non-ambient.d.ts",
"./types/**/$types.d.ts",
"../vite.config.js",
"../vite.config.ts",
"../src/**/*.js",
"../src/**/*.ts",
"../src/**/*.svelte",
"../tests/**/*.js",
"../tests/**/*.ts",
"../tests/**/*.svelte"
],
"exclude": [
"../node_modules/**",
"../src/service-worker.js",
"../src/service-worker/**/*.js",
"../src/service-worker.ts",
"../src/service-worker/**/*.ts",
"../src/service-worker.d.ts",
"../src/service-worker/**/*.d.ts"
]
}其他人需要 SvelteKit 正常运行,除非你了解自己在做什么,否则应保持不变:
{
"compilerOptions": {
// this ensures that types are explicitly
// imported with `import type`, which is
// necessary as Svelte/Vite cannot
// otherwise compile components correctly
"verbatimModuleSyntax": true,
// Vite compiles one TypeScript module
// at a time, rather than compiling
// the entire module graph
"isolatedModules": true,
// Tell TS it's used only for type-checking
"noEmit": true,
// This ensures both `vite build`
// and `svelte-package` work correctly
"lib": ["esnext", "DOM", "DOM.Iterable"],
"moduleResolution": "bundler",
"module": "esnext",
"target": "esnext"
}
}$lib
这是一个简单的别名,指向 src/lib 或指定的任何目录,例如 config.kit.files.lib。它允许您在不使用 ../../../../ 无聊的路径的情况下访问常用组件和实用模块。
$lib/server
子目录位于$lib中。SvelteKit 将阻止您将$lib/server中的任何模块导入到客户端代码中。请参阅仅服务器端模块。
app.d.ts
The app.d.ts 文件是您应用程序的环境类型所在之处,即无需显式导入即可使用的类型。
始终是此文件的一部分是 App 命名空间。此命名空间包含几个影响您交互的某些 SvelteKit 功能的类型的形状。
错误
定义了预期和意外错误的通用形状。预期错误通过使用error函数抛出。意外错误由handleError钩子处理,这些钩子应返回此形状。
接口 Error {/*…*/}
消息:字符串;
本地
接口定义了 event.locals,该变量可在服务器 钩子(handle 和 handleError)、仅服务器 load 函数以及 +server.js 文件中访问。
接口 Locals {}
页面数据
定义了页面数据状态的通用形状以及[ $page.data store](/docs/kit/$ app-stores#page) - 即,所有页面之间共享的数据。在./$types中的Load和ServerLoad函数将被相应地缩小。对于仅在特定页面上存在的数据,使用可选属性。不要添加索引签名([key: string]: any)。
接口 PageData {}
页面状态
页面状态对象 page.state 的形状,可以使用来自 $app/navigation 的 pushState 和 replaceState 函数进行操作。
页面状态接口 {}
平台
如果您的适配器通过 平台特定上下文 通过 event.platform 提供,您可以在此指定它。
平台接口 {}
Edit this page on GitHub llms.txt