类型
生成的类型
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;
局部变量
定义 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 {}
平台
如果你的适配器通过 event.platform
提供 特定于平台的上下文,则可以在这里指定它。
interface Platform {}