型
生成された型
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
予期されるエラーと予期しないエラーの共通の形状を定義します。予期されるエラーはerror
関数を使用してスローされます。予期しないエラーは、この形状を返す必要があるhandleError
フックによって処理されます。
interface Error {…}
message: string;
Locals
サーバーのフック(handle
、handleError
)、サーバー専用のload
関数、および+server.js
ファイルでアクセスできるevent.locals
を定義するインターフェースです。
interface Locals {}
PageData
$page.dataストアの共通の形状、つまりすべてのページ間で共有されるデータを定義します。 ./$types
のLoad
関数とServerLoad
関数は、それに応じて絞り込まれます。特定のページにのみ存在するデータには、オプションのプロパティを使用します。インデックスシグネチャ([key: string]: any
)を追加しないでください。
interface PageData {}
PageState
$app/navigation
のpushState
関数とreplaceState
関数を使用して操作できる$page.state
オブジェクトの形状です。
interface PageState {}
Platform
アダプターがevent.platform
を介してプラットフォーム固有のコンテキストを提供する場合、ここで指定できます。
interface Platform {}