Skip to main content

@sveltejs/kit

import {
	class ServerServer,
	const VERSION: stringVERSION,
	function error(status: number, body: App.Error): never (+1 overload)

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you’re not catching the thrown error, which would prevent SvelteKit from handling it.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError If the provided status is invalid (not between 400 and 599).
error
,
function fail(status: number): ActionFailure<undefined> (+1 overload)

Create an ActionFailure object.

@paramstatus The HTTP status code. Must be in the range 400-599.
fail
,
function isActionFailure(e: unknown): e is ActionFailure

Checks whether this is an action failure thrown by {@link fail } .

@parame The object to check.
isActionFailure
,
function isHttpError<T extends number>(e: unknown, status?: T | undefined): e is (HttpError_1 & {
    status: T extends undefined ? never : T;
})

Checks whether this is an error thrown by {@link error } .

@paramstatus The status to filter for.
isHttpError
,
function isRedirect(e: unknown): e is Redirect_1

Checks whether this is a redirect thrown by {@link redirect } .

@parame The object to check.
isRedirect
,
function json(data: any, init?: ResponseInit | undefined): Response

Create a JSON Response object from the supplied data.

@paramdata The value that will be serialized as JSON.
@paraminit Options such as status and headers that will be added to the response. Content-Type: application/json and Content-Length headers will be added automatically.
json
,
import normalizeUrlnormalizeUrl, function redirect(status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | ({} & number), location: string | URL): never

Redirect a request. When called during request handling, SvelteKit will return a redirect response. Make sure you’re not catching the thrown redirect, which would prevent SvelteKit from handling it.

@paramstatus The HTTP status code. Must be in the range 300-308.
@paramlocation The location to redirect to.
@throwsRedirect This error instructs SvelteKit to redirect to the specified location.
@throwsError If the provided status is invalid.
redirect
,
function text(body: string, init?: ResponseInit | undefined): Response

Create a Response object from the supplied body.

@parambody The value that will be used as-is.
@paraminit Options such as status and headers that will be added to the response. A Content-Length header will be added automatically.
text
} from '@sveltejs/kit';

服务器(Server)

¥Server

class Server {}
constructor(manifest: SSRManifest);
init(options: ServerInitOptions): Promise<void>;
respond(request: Request, options: RequestOptions): Promise<Response>;

VERSION

const VERSION: string;

error

抛出带有 HTTP 状态代码和可选消息的错误。在请求处理期间调用时,这将导致 SvelteKit 返回错误响应而不调用 handleError。确保你没有捕获抛出的错误,否则会阻止 SvelteKit 处理它。

¥Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you’re not catching the thrown error, which would prevent SvelteKit from handling it.

function error(status: number, body: App.Error): never;
function error(
	status: number,
	body?: {
		message: string;
	} extends App.Error
		? App.Error | string | undefined
		: never
): never;

fail

创建 ActionFailure 对象。

¥Create an ActionFailure object.

function fail(status: number): ActionFailure<undefined>;
function fail<
	T extends Record<string, unknown> | undefined = undefined
>(status: number, data: T): ActionFailure<T>;

isActionFailure

检查这是否是 fail 抛出的操作失败。

¥Checks whether this is an action failure thrown by fail.

function isActionFailure(e: unknown): e is ActionFailure;

isHttpError

检查这是否是 error 抛出的错误。

¥Checks whether this is an error thrown by error.

function isHttpError<T extends number>(
	e: unknown,
	status?: T | undefined
): e is HttpError_1 & {
	status: T extends undefined ? never : T;
};

isRedirect

检查这是否是 redirect 抛出的重定向。

¥Checks whether this is a redirect thrown by redirect.

function isRedirect(e: unknown): e is Redirect_1;

json

从提供的数据创建 JSON Response 对象。

¥Create a JSON Response object from the supplied data.

function json(
	data: any,
	init?: ResponseInit | undefined
): Response;

normalizeUrl

自发布起可用 2.18.0

¥Available since 2.18.0

从 URL 路径名中删除可能的 SvelteKit 内部后缀和尾随斜杠。返回规范化的 URL 以及基于新路径名(可能包括搜索)或 URL 添加回潜在后缀的方法。

¥Strips possible SvelteKit-internal suffixes and trailing slashes from the URL pathname. Returns the normalized URL as well as a method for adding the potential suffix back based on a new pathname (possibly including search) or URL.

import { import normalizeUrlnormalizeUrl } from '@sveltejs/kit';

const { const url: anyurl, const denormalize: anydenormalize } = import normalizeUrlnormalizeUrl('/blog/post/__data.json');
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
(const url: anyurl.pathname); // /blog/post
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without calling require('console').

Warning: The global console object’s methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100
log
(const denormalize: anydenormalize('/blog/post/a')); // /blog/post/a/__data.json
function normalizeUrl(url: URL | string): {
	url: URL;
	wasNormalized: boolean;
	denormalize: (url?: string | URL) => URL;
};

redirect

重定向请求。在请求处理期间调用时,SvelteKit 将返回重定向响应。确保你没有捕获抛出的重定向,否则会阻止 SvelteKit 处理它。

¥Redirect a request. When called during request handling, SvelteKit will return a redirect response. Make sure you’re not catching the thrown redirect, which would prevent SvelteKit from handling it.

最常见的状态代码:

¥Most common status codes:

  • 303 See Other:重定向为 GET 请求(通常在表单 POST 请求后使用)

    ¥303 See Other: redirect as a GET request (often used after a form POST request)

  • 307 Temporary Redirect:重定向将保留请求方法

    ¥307 Temporary Redirect: redirect will keep the request method

  • 308 Permanent Redirect:重定向将保留请求方法,SEO 将转移到新页面

    ¥308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page

查看所有重定向状态代码

¥See all redirect status codes

function redirect(
	status:
		| 300
		| 301
		| 302
		| 303
		| 304
		| 305
		| 306
		| 307
		| 308
		| ({} & number),
	location: string | URL
): never;

text

从提供的主体创建 Response 对象。

¥Create a Response object from the supplied body.

function text(
	body: string,
	init?: ResponseInit | undefined
): Response;

操作(Action)

¥Action

+page.server.jsexport const actions = {..} 一部分的表单操作方法的形状。有关更多信息,请参阅 表单操作

¥Shape of a form action method that is part of export const actions = {..} in +page.server.js. See form actions for more information.

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

interface ActionFailure<
	T extends Record<string, unknown> | undefined = undefined
> {}
status: number;
data: T;
[uniqueSymbol]: true;

ActionResult

通过 fetch 调用表单操作时,响应将是这些形状之一。

¥When calling a form action via fetch, the response will be one of these shapes.

<form method="post" use:enhance={() => {
	return ({ result }) => {
		// result is of type ActionResult
	};
}}
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)

¥Actions

+page.server.jsexport const actions = {..} 对象的形状。有关更多信息,请参阅 表单操作

¥Shape of the export const actions = {..} object in +page.server.js. See form actions for more information.

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)

¥Adapter

适配器 负责获取生产版本并将其转变为可以部署到你选择的平台的内容。

¥Adapters are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing.

interface Adapter {}
name: string;

适配器的名称,用于记录。通常与包名称相对应。

¥The name of the adapter, using for logging. Will typically correspond to the package name.

adapt: (builder: Builder) => MaybePromise<void>;
  • builder SvelteKit 提供的对象,包含用于调整应用的方法

    ¥builder An object provided by SvelteKit that contains methods for adapting the app

SvelteKit 构建你的应用后调用此函数。

¥This function is called after SvelteKit has built your app.

supports?: {}

在开发和构建期间调用的检查,以确定特定功能是否可以在生产中使用此适配器

¥Checks called during dev and build to determine whether specific features will work in production with this adapter

read?: (details: { config: any; route: { id: string } }) => boolean;
  • config 合并的路由配置

    ¥config The merged route config

$app/server 测试对 read 的支持

¥Test support for read from $app/server

emulate?: () => MaybePromise<Emulator>;

创建一个 Emulator,允许适配器在开发、构建和预渲染期间影响环境

¥Creates an Emulator, which allows the adapter to influence the environment during dev, build and prerendering

AfterNavigate

传递给 afterNavigate 回调的参数。

¥The argument passed to afterNavigate callbacks.

interface AfterNavigate extends Omit<Navigation, 'type'> {}
type: Exclude<NavigationType, 'leave'>;

导航类型:

¥The type of navigation:

  • enter:应用已水化

    ¥enter: The app has hydrated

  • form:用户提交了 <form>

    ¥form: The user submitted a <form>

  • link:导航由链接单击触发

    ¥link: Navigation was triggered by a link click

  • goto:导航由 goto(...) 调用或重定向触发

    ¥goto: Navigation was triggered by a goto(...) call or a redirect

  • popstate:导航由后退/前进导航触发

    ¥popstate: Navigation was triggered by back/forward navigation

willUnload: false;

由于 afterNavigate 回调是在导航完成后调用的,因此它们永远不会在卸载页面的导航中被调用。

¥Since afterNavigate callbacks are called after a navigation completes, they will never be called with a navigation that unloads the page.

AwaitedActions

type AwaitedActions<
	T extends Record<string, (...args: any) => any>
> = OptionalUnion<
	{
		[Key in keyof T]: UnpackValidationError<
			Awaited<ReturnType<T[Key]>>
		>;
	}[keyof T]
>;

BeforeNavigate

传递给 beforeNavigate 回调的参数。

¥The argument passed to beforeNavigate callbacks.

interface BeforeNavigate extends Navigation {}
cancel: () => void;

调用此方法可防止导航启动。

¥Call this to prevent the navigation from starting.

构建器(Builder)

¥Builder

此对象传递给适配器的 adapt 函数。它包含各种方法和属性,可用于调整应用。

¥This object is passed to the adapt function of adapters. It contains various methods and properties that are useful for adapting the app.

interface Builder {}
log: Logger;

将消息打印到控制台。除非 Vite 的 logLevelinfo,否则 log.infolog.minor 是静默的。

¥Print messages to the console. log.info and log.minor are silent unless Vite’s logLevel is info.

rimraf: (dir: string) => void;

删除 dir 及其所有内容。

¥Remove dir and all its contents.

mkdirp: (dir: string) => void;

创建 dir 和任何所需的父目录。

¥Create dir and any required parent directories.

config: ValidatedConfig;

完全解析的 svelte.config.js

¥The fully resolved svelte.config.js.

prerendered: Prerendered;

有关预渲染页面和资源的信息(如果有)。

¥Information about prerendered pages and assets, if any.

routes: RouteDefinition[];

所有路由(包括预渲染)的数组

¥An array of all routes (including prerendered)

createEntries: (fn: (route: RouteDefinition) => AdapterEntry) => Promise<void>;
  • fn 将一组路由分组到入口点的函数

    ¥fn A function that groups a set of routes into an entry point

  • 已弃用 改用 builder.routes

    ¥deprecated Use builder.routes instead

创建映射到应用一个或多个路由的单独函数。

¥Create separate functions that map to one or more routes of your app.

findServerAssets: (routes: RouteDefinition[]) => string[];

查找属于 routes 的服务器文件导入的所有资源

¥Find all the assets imported by server files belonging to routes

generateFallback: (dest: string) => Promise<void>;

为静态 Web 服务器生成一个后备页面,以便在没有匹配路由时使用。适用于单页应用。

¥Generate a fallback page for a static webserver to use when no route is matched. Useful for single-page apps.

generateEnvModule: () => void;

生成一个将构建时环境变量公开为 $env/dynamic/public 的模块。

¥Generate a module exposing build-time environment variables as $env/dynamic/public.

generateManifest: (opts: { relativePath: string; routes?: RouteDefinition[] }) => string;
  • opts 应用基目录的相对路径,以及可选的清单生成格式(esm 或 cjs)

    ¥opts a relative path to the base directory of the app and optionally in which format (esm or cjs) the manifest should be generated

生成服务器端清单以初始化 SvelteKit server

¥Generate a server-side manifest to initialise the SvelteKit server with.

getBuildDirectory: (name: string) => string;
  • name 相对于构建目录的文件路径

    ¥name path to the file, relative to the build directory

解析 outDirname 目录的路径,例如 /path/to/.svelte-kit/my-adapter

¥Resolve a path to the name directory inside outDir, e.g. /path/to/.svelte-kit/my-adapter.

getClientDirectory: () => string;

获取包含客户端资源的目录的完整解析路径,包括 static 目录的内容。

¥Get the fully resolved path to the directory containing client-side assets, including the contents of your static directory.

getServerDirectory: () => string;

获取包含服务器端代码的目录的完整解析路径。

¥Get the fully resolved path to the directory containing server-side code.

getAppPath: () => string;

获取应用路径,包括任何配置的 base 路径,例如 my-base-path/_app

¥Get the application path including any configured base path, e.g. my-base-path/_app.

writeClient: (dest: string) => string[];
  • dest 目标文件夹

    ¥dest the destination folder

  • 返回 写入 dest 的文件数组

    ¥returns an array of files written to dest

将客户端资源写入 dest

¥Write client assets to dest.

writePrerendered: (dest: string) => string[];
  • dest 目标文件夹

    ¥dest the destination folder

  • 返回 写入 dest 的文件数组

    ¥returns an array of files written to dest

将预渲染文件写入 dest

¥Write prerendered files to dest.

writeServer: (dest: string) => string[];
  • dest 目标文件夹

    ¥dest the destination folder

  • 返回 写入 dest 的文件数组

    ¥returns an array of files written to dest

将服务器端代码写入 dest

¥Write server-side code to dest.

copy: (
	from: string,
	to: string,
	opts?: {
		filter?(basename: string): boolean;
		replace?: Record<string, string>;
	}
) => string[];
  • from 源文件或目录

    ¥from the source file or directory

  • to 目标文件或目录

    ¥to the destination file or directory

  • opts.filter 一个函数,用于确定是否应复制文件或目录

    ¥opts.filter a function to determine whether a file or directory should be copied

  • opts.replace 要替换的字符串映射

    ¥opts.replace a map of strings to replace

  • 返回 已复制的文件数组

    ¥returns an array of files that were copied

复制文件或目录。

¥Copy a file or directory.

compress: (directory: string) => Promise<void>;
  • directory 包含要压缩的文件的目录

    ¥directory The directory containing the files to be compressed

在适当的情况下,使用 gzip 和 brotli 压缩 directory 中的文件。与原始文件一起生成 .gz.br 文件。

¥Compress files in directory with gzip and brotli, where appropriate. Generates .gz and .br files alongside the originals.

ClientInit

自 2.10.0 起可用

¥Available since 2.10.0

一旦应用在浏览器中启动,将调用 init

¥The init will be invoked once the app starts in the browser

type ClientInit = () => MaybePromise<void>;

配置(Config)

¥Config

有关详细信息,请参阅 配置参考

¥See the configuration reference for details.

Cookies

interface Cookies {}
get: (name: string, opts?: import('cookie').CookieParseOptions) => string | undefined;
  • name cookie 的名称

    ¥name the name of the cookie

  • opts 选项,直接传递给 cookie.parse。参见文档 此处

    ¥opts the options, passed directly to cookie.parse. See documentation here

获取先前使用 cookies.set 设置的 cookie,或从请求标头中获取。

¥Gets a cookie that was previously set with cookies.set, or from the request headers.

getAll: (opts?: import('cookie').CookieParseOptions) => Array<{ name: string; value: string }>;
  • opts 选项,直接传递给 cookie.parse。参见文档 此处

    ¥opts the options, passed directly to cookie.parse. See documentation here

获取先前使用 cookies.set 设置的 cookie,或从请求标头中获取所有 cookie。

¥Gets all cookies that were previously set with cookies.set, or from the request headers.

set: (
	name: string,
	value: string,
	opts: import('cookie').CookieSerializeOptions & { path: string }
) => void;
  • name cookie 的名称

    ¥name the name of the cookie

  • value cookie 值

    ¥value the cookie value

  • opts 选项,直接传递给 cookie.serialize。参见文档 此处

    ¥opts the options, passed directly to cookie.serialize. See documentation here

设置 cookie。这将向响应添加 set-cookie 标头,但也使 cookie 在当前请求期间通过 cookies.getcookies.getAll 可用。

¥Sets a cookie. This will add a set-cookie header to the response, but also make the cookie available via cookies.get or cookies.getAll during the current request.

httpOnlysecure 选项默认为 truehttp://localhost 除外,其中 securefalse),如果你希望 cookie 可被客户端 JavaScript 读取和/或通过 HTTP 传输,则必须明确禁用它们。sameSite 选项默认为 lax

¥The httpOnly and secure options are true by default (except on http://localhost, where secure is false), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults to lax.

你必须为 cookie 指定 path。在大多数情况下,你应该明确设置 path: '/' 以使 cookie 在整个应用中可用。你可以使用相对路径,或设置 path: '' 以使 cookie 仅在当前路径及其子路径上可用

¥You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children

delete: (name: string, opts: import('cookie').CookieSerializeOptions & { path: string }) => void;
  • name cookie 的名称

    ¥name the name of the cookie

  • opts 选项,直接传递给 cookie.serializepath 必须与你要删除的 cookie 的路径匹配。参见文档 此处

    ¥opts the options, passed directly to cookie.serialize. The path must match the path of the cookie you want to delete. See documentation here

通过将其值设置为空字符串并将到期日期设置为过去来删除 cookie。

¥Deletes a cookie by setting its value to an empty string and setting the expiry date in the past.

你必须为 cookie 指定 path。在大多数情况下,你应该明确设置 path: '/' 以使 cookie 在整个应用中可用。你可以使用相对路径,或设置 path: '' 以使 cookie 仅在当前路径及其子路径上可用

¥You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children

serialize: (
	name: string,
	value: string,
	opts: import('cookie').CookieSerializeOptions & { path: string }
) => string;
  • name cookie 的名称

    ¥name the name of the cookie

  • value cookie 值

    ¥value the cookie value

  • opts 选项,直接传递给 cookie.serialize。参见文档 此处

    ¥opts the options, passed directly to cookie.serialize. See documentation here

将 cookie 名称-值对序列化为 Set-Cookie 标头字符串,但不将其应用于响应。

¥Serialize a cookie name-value pair into a Set-Cookie header string, but don’t apply it to the response.

httpOnlysecure 选项默认为 truehttp://localhost 除外,其中 securefalse),如果你希望 cookie 可被客户端 JavaScript 读取和/或通过 HTTP 传输,则必须明确禁用它们。sameSite 选项默认为 lax

¥The httpOnly and secure options are true by default (except on http://localhost, where secure is false), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults to lax.

你必须为 cookie 指定 path。在大多数情况下,你应该明确设置 path: '/' 以使 cookie 在整个应用中可用。你可以使用相对路径,或设置 path: '' 以使 cookie 仅在当前路径及其子路径上可用

¥You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children

模拟器(Emulator)

¥Emulator

在开发、构建和预渲染期间影响环境的函数集合

¥A collection of functions that influence the environment during dev, build and prerendering

interface Emulator {}
platform?(details: { config: any; prerender: PrerenderOption }): MaybePromise<App.Platform>;

使用当前路由 configprerender 选项调用并返回 App.Platform 对象的函数

¥A function that is called with the current route config and prerender option and returns an App.Platform object

句柄(Handle)

¥Handle

每次 SvelteKit 服务器收到 request 并确定 response 时,handle 钩子都会运行。它接收一个代表请求的 event 对象和一个名为 resolve 的函数,该函数渲染路由并生成 Response。这允许你修改响应标头或正文,或完全绕过 SvelteKit(例如,以编程方式实现路由)。

¥The handle hook runs every time the SvelteKit server receives a request and determines the response. It receives an event object representing the request and a function called resolve, which renders the route and generates a Response. This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).

type Handle = (input: {
	event: RequestEvent;
	resolve: (
		event: RequestEvent,
		opts?: ResolveOptions
	) => MaybePromise<Response>;
}) => MaybePromise<Response>;

HandleClientError

当导航时出现意外错误时,客户端 handleError 钩子会运行。

¥The client-side handleError hook runs when an unexpected error is thrown while navigating.

如果在加载或随后的渲染期间抛出意外错误,则将使用错误和事件调用此函数。确保此函数永远不会抛出错误。

¥If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event. Make sure that this function never throws an error.

type HandleClientError = (input: {
	error: unknown;
	event: NavigationEvent;
	status: number;
	message: string;
}) => MaybePromise<void | App.Error>;

HandleFetch

handleFetch 钩子允许你修改(或替换)在服务器上运行的 load 函数内部发生的 fetch 请求(或在预渲染期间)

¥The handleFetch hook allows you to modify (or replace) a fetch request that happens inside a load function that runs on the server (or during pre-rendering)

type HandleFetch = (input: {
	event: RequestEvent;
	request: Request;
	fetch: typeof fetch;
}) => MaybePromise<Response>;

HandleServerError

当响应请求时出现意外错误时,服务器端 handleError 钩子会运行。

¥The server-side handleError hook runs when an unexpected error is thrown while responding to a request.

如果在加载或渲染期间抛出意外错误,则将使用错误和事件调用此函数。确保此函数永远不会抛出错误。

¥If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event. Make sure that this function never throws an error.

type HandleServerError = (input: {
	error: unknown;
	event: RequestEvent;
	status: number;
	message: string;
}) => MaybePromise<void | App.Error>;

HttpError

error 函数返回的对象。

¥The object returned by the error function.

interface HttpError {}
status: number;

HTTP 状态代码,范围为 400-599。

¥The HTTP status code, in the range 400-599.

body: App.Error;

错误的内容。

¥The content of the error.

KitConfig

有关详细信息,请参阅 配置参考

¥See the configuration reference for details.

LessThan

type LessThan<
	TNumber extends number,
	TArray extends any[] = []
> = TNumber extends TArray['length']
	? TArray[number]
	: LessThan<TNumber, [...TArray, TArray['length']]>;

加载(Load)

¥Load

PageLoadLayoutLoad 的通用形式。你应该从 ./$types 导入这些(参见 生成的类型),而不是直接使用 Load

¥The generic form of PageLoad and LayoutLoad. You should import those from ./$types (see generated types) rather than using Load directly.

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

PageLoadEventLayoutLoadEvent 的通用形式。你应该从 ./$types 导入这些(参见 生成的类型),而不是直接使用 LoadEvent

¥The generic form of PageLoadEvent and LayoutLoadEvent. You should import those from ./$types (see generated types) rather than using LoadEvent directly.

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> {}
fetch: typeof fetch;

fetch 等同于 原生 fetch Web API,但具有一些附加功能:

¥fetch is equivalent to the native fetch web API, with a few additional features:

  • 它可用于在服务器上发出凭证请求,因为它继承了页面请求的 cookieauthorization 标头。

    ¥It can be used to make credentialed requests on the server, as it inherits the cookie and authorization headers for the page request.

  • 它可以在服务器上发出相对请求(通常,fetch 在服务器上下文中使用时需要具有来源的 URL)。

    ¥It can make relative requests on the server (ordinarily, fetch requires a URL with an origin when used in a server context).

  • 内部请求(例如,对于 +server.js 路由)在服务器上运行时直接转到处理程序函数,而无需 HTTP 调用的开销。

    ¥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.

  • 在服务器端渲染过程中,响应将通过挂接到 Response 对象的 textjson 方法中被捕获并内联到渲染的 HTML 中。请注意,除非通过 filterSerializedResponseHeaders 明确包含,否则不会序列化标头

    ¥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

  • 在 hydration 期间,将从 HTML 中读取响应,以保证一致性并防止额外的网络请求。

    ¥During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.

你可以了解有关使用 cookie 此处 发出凭证请求的更多信息

¥You can learn more about making credentialed requests with cookies here

data: Data;

包含路由的服务器 load 函数(在 +layout.server.js+page.server.js 中)返回的数据(如果有)。

¥Contains the data returned by the route’s server load function (in +layout.server.js or +page.server.js), if any.

setHeaders: (headers: Record<string, string>) => void;

如果你需要为响应设置标头,则可以使用此方法进行设置。如果你希望缓存页面,这将非常有用,例如:

¥If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:

src/routes/blog/+page
export async function 
function load({ fetch, setHeaders }: {
    fetch: any;
    setHeaders: any;
}): Promise<any>
load
({ fetch, setHeaders }) {
const const url: "https://cms.example.com/articles.json"url = `https://cms.example.com/articles.json`; const const response: anyresponse = await fetch: anyfetch(const url: "https://cms.example.com/articles.json"url); setHeaders: anysetHeaders({ age: anyage: const response: anyresponse.headers.get('age'), 'cache-control': const response: anyresponse.headers.get('cache-control') }); return const response: anyresponse.json(); }

多次设置相同的标头(即使在单独的 load 函数中)是错误的 - 你只能设置一次给定的标头。

¥Setting the same header multiple times (even in separate load functions) is an error — you can only set a given header once.

你不能使用 setHeaders 添加 set-cookie 标头 — 改用服务器专用 load 函数中的 cookies API。

¥You cannot add a set-cookie header with setHeaders — use the cookies API in a server-only load function instead.

load 函数在浏览器中运行时,setHeaders 不起作用。

¥setHeaders has no effect when a load function runs in the browser.

parent: () => Promise<ParentData>;

await parent() 从父 +layout.js load 函数返回数据。隐式地,缺少的 +layout.js 被视为 ({ data }) => data 函数,这意味着它将返回并转发来自父 +layout.server.js 文件的数据。

¥await parent() returns data from parent +layout.js load functions. Implicitly, a missing +layout.js is treated as a ({ data }) => data function, meaning that it will return and forward data from parent +layout.server.js files.

使用 await parent() 时,请注意不要引入意外瀑布。例如,如果你只想将父数据合并到返回的输出中,请在获取其他数据后调用它。

¥Be careful not to introduce accidental waterfalls when using await parent(). If for example you only want to merge parent data into the returned output, call it after fetching your other data.

depends: (...deps: Array<`${string}:${string}`>) => void;

此函数声明 load 函数依赖于一个或多个 URL 或自定义标识符,随后可将其与 invalidate() 一起使用以导致 load 重新运行。

¥This function declares that the load function has a dependency on one or more URLs or custom identifiers, which can subsequently be used with invalidate() to cause load to rerun.

大多数时候你不需要这个,因为 fetch 会代表你调用 depends — 只有在你使用绕过 fetch 的自定义 API 客户端时才需要。

¥Most of the time you won’t need this, as fetch calls depends on your behalf — it’s only necessary if you’re using a custom API client that bypasses fetch.

URL 可以是绝对的,也可以是相对于正在加载的页面的相对的,并且必须是 encoded

¥URLs can be absolute or relative to the page being loaded, and must be encoded.

自定义标识符必须以一个或多个小写字母作为前缀,后跟冒号,以符合 URI 规范

¥Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the URI specification.

以下示例显示如何使用 depends 注册对自定义标识符的依赖,该标识符在按钮单击后为 invalidated,从而使 load 函数重新运行。

¥The following example shows how to use depends to register a dependency on a custom identifier, which is invalidated after a button click, making the load function rerun.

src/routes/+page
let let count: numbercount = 0;
export async function 
function load({ depends }: {
    depends: any;
}): Promise<{
    count: number;
}>
load
({ depends }) {
depends: anydepends('increase:count'); return { count: numbercount: let count: numbercount++ }; }
src/routes/+page
<script>
	import { invalidate } from '$app/navigation';

	let { data } = $props();

	const increase = async () => {
		await invalidate('increase:count');
	}
</script>

<p>{data.count}<p>
<button on:click={increase}>Increase Count</button>
untrack: <T>(fn: () => T) => T;

使用此功能选择退出回调中同步调用的所有内容的依赖跟踪。示例:

¥Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:

src/routes/+page.server
export async function 
function load({ untrack, url }: {
    untrack: any;
    url: any;
}): Promise<{
    message: string;
} | undefined>
load
({ untrack, url }) {
// Untrack url.pathname so that path changes don't trigger a rerun if (untrack: anyuntrack(() => url: anyurl.pathname === '/')) { return { message: stringmessage: 'Welcome!' }; } }

LoadProperties

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)

¥Navigation

interface Navigation {}
from: NavigationTarget | null;

导航从哪里触发

¥Where navigation was triggered from

to: NavigationTarget | null;

导航将要/已经到达的位置

¥Where navigation is going to/has gone to

type: Exclude<NavigationType, 'enter'>;

导航类型:

¥The type of navigation:

  • form:用户提交了 <form>

    ¥form: The user submitted a <form>

  • leave:离开应用是因为选项卡已关闭或正在导航到其他文档

    ¥leave: The app is being left either because the tab is being closed or a navigation to a different document is occurring

  • link:导航由链接单击触发

    ¥link: Navigation was triggered by a link click

  • goto:导航由 goto(...) 调用或重定向触发

    ¥goto: Navigation was triggered by a goto(...) call or a redirect

  • popstate:导航由后退/前进导航触发

    ¥popstate: Navigation was triggered by back/forward navigation

willUnload: boolean;

导航是否会导致页面被卸载(即不是客户端导航)

¥Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation)

delta?: number;

在历史记录后退/前进导航的情况下,后退/前进的步骤数

¥In case of a history back/forward navigation, the number of steps to go back/forward

complete: Promise<void>;

导航完成后,promise 将得到解决;导航失败或中止时,promise 将拒绝。在 willUnload 导航的情况下,promise 永远不会解决

¥A promise that resolves once the navigation is complete, and rejects if the navigation fails or is aborted. In the case of a willUnload navigation, the promise will never resolve

interface NavigationEvent<
	Params extends Partial<Record<string, string>> = Partial<
		Record<string, string>
	>,
	RouteId extends string | null = string | null
> {}
params: Params;

当前页面的参数 - 例如,对于像 /blog/[slug] 这样的路由,一个 { slug: string } 对象

¥The parameters of the current page - e.g. for a route like /blog/[slug], a { slug: string } object

route: {}

有关当前路由的信息

¥Info about the current route

id: RouteId;

当前路由的 ID - 例如对于 src/routes/blog/[slug],它将是 /blog/[slug]

¥The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug]

url: URL;

当前页面的 URL

¥The URL of the current page

有关特定导航目标的信息。

¥Information about the target of a specific navigation.

interface NavigationTarget {}
params: Record<string, string> | null;

目标页面的参数 - 例如,对于像 /blog/[slug] 这样的路由,一个 { slug: string } 对象。如果目标不是 SvelteKit 应用的一部分(无法解析为路由),则为 null

¥Parameters of the target page - e.g. for a route like /blog/[slug], a { slug: string } object. Is null if the target is not part of the SvelteKit app (could not be resolved to a route).

route: { id: string | null };

有关目标路由的信息

¥Info about the target route

url: URL;

导航到的 URL

¥The URL that is navigated to

  • enter:应用已水化

    ¥enter: The app has hydrated

  • form:用户使用 GET 方法提交了 <form>

    ¥form: The user submitted a <form> with a GET method

  • leave:用户通过关闭选项卡或使用后退/前进按钮转到其他文档来离开应用

    ¥leave: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document

  • link:导航由链接单击触发

    ¥link: Navigation was triggered by a link click

  • goto:导航由 goto(...) 调用或重定向触发

    ¥goto: Navigation was triggered by a goto(...) call or a redirect

  • popstate:导航由后退/前进导航触发

    ¥popstate: Navigation was triggered by back/forward navigation

type NavigationType =
	| 'enter'
	| 'form'
	| 'leave'
	| 'link'
	| 'goto'
	| 'popstate';

NumericRange

type NumericRange<
	TStart extends number,
	TEnd extends number
> = Exclude<TEnd | LessThan<TEnd>, LessThan<TStart>>;

OnNavigate

传递给 onNavigate 回调的参数。

¥The argument passed to onNavigate callbacks.

interface OnNavigate extends Navigation {}
type: Exclude<NavigationType, 'enter' | 'leave'>;

导航类型:

¥The type of navigation:

  • form:用户提交了 <form>

    ¥form: The user submitted a <form>

  • link:导航由链接单击触发

    ¥link: Navigation was triggered by a link click

  • goto:导航由 goto(...) 调用或重定向触发

    ¥goto: Navigation was triggered by a goto(...) call or a redirect

  • popstate:导航由后退/前进导航触发

    ¥popstate: Navigation was triggered by back/forward navigation

willUnload: false;

由于 onNavigate 回调是在客户端导航之前立即调用的,因此它们永远不会在卸载页面的导航中被调用。

¥Since onNavigate callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.

页面(Page)

¥Page

page 反应对象和 $page 存储的形状。

¥The shape of the page reactive object and the $page store.

interface Page<
	Params extends Record<string, string> = Record<
		string,
		string
	>,
	RouteId extends string | null = string | null
> {}
url: URL;

当前页面的 URL。

¥The URL of the current page.

params: Params;

当前页面的参数 - 例如,对于像 /blog/[slug] 这样的路由,一个 { slug: string } 对象。

¥The parameters of the current page - e.g. for a route like /blog/[slug], a { slug: string } object.

route: {}

有关当前路由的信息。

¥Info about the current route.

id: RouteId;

当前路由的 ID - 例如,对于 src/routes/blog/[slug],它将是 /blog/[slug]

¥The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug].

status: number;

当前页面的 HTTP 状态代码。

¥HTTP status code of the current page.

error: App.Error | null;

当前页面的错误对象(如果有)。从 handleError 钩子填充。

¥The error object of the current page, if any. Filled from the handleError hooks.

data: App.PageData & Record<string, any>;

当前页面上所有 load 函数的所有数据的合并结果。你可以通过 App.PageData 输入公分母。

¥The merged result of all data from all load functions on the current page. You can type a common denominator through App.PageData.

state: App.PageState;

页面状态,可以使用 $app/navigation 中的 pushStatereplaceState 函数进行操作。

¥The page state, which can be manipulated using the pushState and replaceState functions from $app/navigation.

form: any;

仅在表单提交后填充。有关更多信息,请参阅 表单操作

¥Filled only after a form submission. See form actions for more info.

ParamMatcher

参数匹配器的形状。有关更多信息,请参阅 matching

¥The shape of a param matcher. See matching for more info.

type ParamMatcher = (param: string) => boolean;

PrerenderOption

type PrerenderOption = boolean | 'auto';

重定向(Redirect)

¥Redirect

redirect 函数返回的对象。

¥The object returned by the redirect function.

interface Redirect {}
status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;

HTTP 状态代码,在 300-308 范围内。

¥The HTTP status code, in the range 300-308.

location: string;

重定向到的位置。

¥The location to redirect to.

RequestEvent

interface RequestEvent<
	Params extends Partial<Record<string, string>> = Partial<
		Record<string, string>
	>,
	RouteId extends string | null = string | null
> {}
cookies: Cookies;

获取或设置与当前请求相关的 cookie

¥Get or set cookies related to the current request

fetch: typeof fetch;

fetch 等同于 原生 fetch Web API,但具有一些附加功能:

¥fetch is equivalent to the native fetch web API, with a few additional features:

  • 它可用于在服务器上发出凭证请求,因为它继承了页面请求的 cookieauthorization 标头。

    ¥It can be used to make credentialed requests on the server, as it inherits the cookie and authorization headers for the page request.

  • 它可以在服务器上发出相对请求(通常,fetch 在服务器上下文中使用时需要具有来源的 URL)。

    ¥It can make relative requests on the server (ordinarily, fetch requires a URL with an origin when used in a server context).

  • 内部请求(例如,对于 +server.js 路由)在服务器上运行时直接转到处理程序函数,而无需 HTTP 调用的开销。

    ¥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.

  • 在服务器端渲染过程中,响应将通过挂接到 Response 对象的 textjson 方法中被捕获并内联到渲染的 HTML 中。请注意,除非通过 filterSerializedResponseHeaders 明确包含,否则不会序列化标头

    ¥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

  • 在 hydration 期间,将从 HTML 中读取响应,以保证一致性并防止额外的网络请求。

    ¥During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.

你可以了解有关使用 cookie 此处 发出凭证请求的更多信息。

¥You can learn more about making credentialed requests with cookies here.

getClientAddress: () => string;

由适配器设置的客户端 IP 地址。

¥The client’s IP address, set by the adapter.

locals: App.Locals;

包含在 server handle hook 内添加到请求的自定义数据。

¥Contains custom data that was added to the request within the server handle hook.

params: Params;

当前路由的参数 - 例如,对于像 /blog/[slug] 这样的路由,一个 { slug: string } 对象。

¥The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.

platform: Readonly<App.Platform> | undefined;

通过适配器提供的其他数据。

¥Additional data made available through the adapter.

request: Request;

原始请求对象。

¥The original request object.

route: {}

有关当前路由的信息。

¥Info about the current route.

id: RouteId;

当前路由的 ID - 例如,对于 src/routes/blog/[slug],它将是 /blog/[slug]

¥The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug].

setHeaders: (headers: Record<string, string>) => void;

如果你需要为响应设置标头,则可以使用此方法进行设置。如果你希望缓存页面,这将非常有用,例如:

¥If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:

src/routes/blog/+page
export async function 
function load({ fetch, setHeaders }: {
    fetch: any;
    setHeaders: any;
}): Promise<any>
load
({ fetch, setHeaders }) {
const const url: "https://cms.example.com/articles.json"url = `https://cms.example.com/articles.json`; const const response: anyresponse = await fetch: anyfetch(const url: "https://cms.example.com/articles.json"url); setHeaders: anysetHeaders({ age: anyage: const response: anyresponse.headers.get('age'), 'cache-control': const response: anyresponse.headers.get('cache-control') }); return const response: anyresponse.json(); }

多次设置相同的标头(即使在单独的 load 函数中)是错误的 - 你只能设置一次给定的标头。

¥Setting the same header multiple times (even in separate load functions) is an error — you can only set a given header once.

你不能使用 setHeaders 添加 set-cookie 标头 — 改用 cookies API。

¥You cannot add a set-cookie header with setHeaders — use the cookies API instead.

url: URL;

请求的 URL。

¥The requested URL.

isDataRequest: boolean;

如果请求来自请求 +page/layout.server.js 数据的客户端,则为 true。在这种情况下,url 属性将被剥离与数据请求相关的内部信息。如果区别对你很重要,请改用此属性。

¥true if the request comes from the client asking for +page/layout.server.js data. The url property will be stripped of the internal information related to the data request in this case. Use this property instead if the distinction is important to you.

isSubRequest: boolean;

true 用于来自 SvelteKit 的 +server.js 调用,而无需实际发出 HTTP 请求的开销。当你在服务器上发出同源 fetch 请求时,就会发生这种情况。

¥true for +server.js calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin fetch requests on the server.

RequestHandler

+server.js 文件导出的 (event: RequestEvent) => Response 函数对应于 HTTP 动词(GETPUTPATCH 等)并使用该方法处理请求。

¥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.

它接收 Params 作为第一个通用参数,你可以通过使用 生成的类型 来跳过它。

¥It receives Params as the first generic argument, which you can skip by using generated types instead.

type RequestHandler<
	Params extends Partial<Record<string, string>> = Partial<
		Record<string, string>
	>,
	RouteId extends string | null = string | null
> = (
	event: RequestEvent<Params, RouteId>
) => MaybePromise<Response>;

重新路由(Reroute)

¥Reroute

自 2.3.0 起可用

¥Available since 2.3.0

reroute 钩子允许你在 URL 用于确定要渲染的路由之前对其进行修改。

¥The reroute hook allows you to modify the URL before it is used to determine which route to render.

type Reroute = (event: {
	url: URL;
}) => MaybePromise<void | string>;

ResolveOptions

interface ResolveOptions {}
transformPageChunk?: (input: { html: string; done: boolean }) => MaybePromise<string | undefined>;
  • input html 块和信息(如果这是最后一个块)

    ¥input the html chunk and the info if this is the last chunk

将自定义转换应用于 HTML。如果 done 为真,则它是最终块。块不能保证是格式正确的 HTML(例如,它们可能包含元素的开始标记但不包含结束标记),但它们始终会在合理的边界处进行拆分,例如 %sveltekit.head% 或布局/页面组件。

¥Applies custom transforms to HTML. If done is true, it’s the final chunk. Chunks are not guaranteed to be well-formed HTML (they could include an element’s opening tag but not its closing tag, for example) but they will always be split at sensible boundaries such as %sveltekit.head% or layout/page components.

filterSerializedResponseHeaders?: (name: string, value: string) => boolean;
  • name 标头名称

    ¥name header name

  • value 标头值

    ¥value header value

确定当 load 函数使用 fetch 加载资源时,应在序列化响应中包含哪些标头。默认情况下,不会包含任何内容。

¥Determines which headers should be included in serialized responses when a load function loads a resource with fetch. By default, none will be included.

preload?: (input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }) => boolean;
  • input 文件的类型及其路径

    ¥input the type of the file and its path

确定应将什么添加到 <head> 标签以预加载它。默认情况下,jscss 文件将被预加载。

¥Determines what should be added to the <head> tag to preload it. By default, js and css files will be preloaded.

RouteDefinition

interface RouteDefinition<Config = any> {}
id: string;
api: {
	methods: Array<HttpMethod | '*'>;
};
page: {
	methods: Array<Extract<HttpMethod, 'GET' | 'POST'>>;
};
pattern: RegExp;
prerender: PrerenderOption;
segments: RouteSegment[];
methods: Array<HttpMethod | '*'>;
config: Config;

SSRManifest

interface SSRManifest {}
appDir: string;
appPath: string;
assets: Set<string>;

来自 kit.config.files.assets 和服务工作者(如果有)的静态文件。

¥Static files from kit.config.files.assets and the service worker (if any).

mimeTypes: Record<string, string>;
_: {}

将代码放在靠近使用位置的位置

¥private fields

client: NonNullable<BuildData['client']>;
nodes: SSRNodeLoader[];
routes: SSRRoute[];
prerendered_routes: Set<string>;
matchers: () => Promise<Record<string, ParamMatcher>>;
server_assets: Record<string, number>;

服务器代码导入的所有资源的 [file]: size 映射。

¥A [file]: size map of all assets imported by server code.

ServerInit

自 2.10.0 起可用

¥Available since 2.10.0

在服务器响应其第一个请求之前将调用 init

¥The init will be invoked before the server responds to its first request

type ServerInit = () => MaybePromise<void>;

ServerInitOptions

interface ServerInitOptions {}
env: Record<string, string>;

环境变量映射。

¥A map of environment variables.

read?: (file: string) => ReadableStream;

将资源文件名转换为 ReadableStream 的函数。read$app/server 导出需要此设置才能正常工作。

¥A function that turns an asset filename into a ReadableStream. Required for the read export from $app/server to work.

ServerLoad

PageServerLoadLayoutServerLoad 的通用形式。你应该从 ./$types 导入这些(参见 生成的类型),而不是直接使用 ServerLoad

¥The generic form of PageServerLoad and LayoutServerLoad. You should import those from ./$types (see generated types) rather than using ServerLoad directly.

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>;

ServerLoadEvent

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> {}
parent: () => Promise<ParentData>;

await parent() 从父 +layout.server.js load 函数返回数据。

¥await parent() returns data from parent +layout.server.js load functions.

使用 await parent() 时,请注意不要引入意外瀑布。例如,如果你只想将父数据合并到返回的输出中,请在获取其他数据后调用它。

¥Be careful not to introduce accidental waterfalls when using await parent(). If for example you only want to merge parent data into the returned output, call it after fetching your other data.

depends: (...deps: string[]) => void;

此函数声明 load 函数依赖于一个或多个 URL 或自定义标识符,随后可将其与 invalidate() 一起使用以导致 load 重新运行。

¥This function declares that the load function has a dependency on one or more URLs or custom identifiers, which can subsequently be used with invalidate() to cause load to rerun.

大多数时候你不需要这个,因为 fetch 会代表你调用 depends — 只有在你使用绕过 fetch 的自定义 API 客户端时才需要。

¥Most of the time you won’t need this, as fetch calls depends on your behalf — it’s only necessary if you’re using a custom API client that bypasses fetch.

URL 可以是绝对的,也可以是相对于正在加载的页面的相对的,并且必须是 encoded

¥URLs can be absolute or relative to the page being loaded, and must be encoded.

自定义标识符必须以一个或多个小写字母作为前缀,后跟冒号,以符合 URI 规范

¥Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the URI specification.

以下示例显示如何使用 depends 注册对自定义标识符的依赖,该标识符在按钮单击后为 invalidated,从而使 load 函数重新运行。

¥The following example shows how to use depends to register a dependency on a custom identifier, which is invalidated after a button click, making the load function rerun.

src/routes/+page
let let count: numbercount = 0;
export async function 
function load({ depends }: {
    depends: any;
}): Promise<{
    count: number;
}>
load
({ depends }) {
depends: anydepends('increase:count'); return { count: numbercount: let count: numbercount++ }; }
src/routes/+page
<script>
	import { invalidate } from '$app/navigation';

	let { data } = $props();

	const increase = async () => {
		await invalidate('increase:count');
	}
</script>

<p>{data.count}<p>
<button on:click={increase}>Increase Count</button>
untrack: <T>(fn: () => T) => T;

使用此功能选择退出回调中同步调用的所有内容的依赖跟踪。示例:

¥Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:

src/routes/+page
export async function 
function load({ untrack, url }: {
    untrack: any;
    url: any;
}): Promise<{
    message: string;
} | undefined>
load
({ untrack, url }) {
// Untrack url.pathname so that path changes don't trigger a rerun if (untrack: anyuntrack(() => url: anyurl.pathname === '/')) { return { message: stringmessage: 'Welcome!' }; } }

快照(Snapshot)

¥Snapshot

从页面或布局组件导出的 export const snapshot 类型。

¥The type of export const snapshot exported from a page or layout component.

interface Snapshot<T = any> {}
capture: () => T;
restore: (snapshot: T) => void;

SubmitFunction

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>;
	  }) => MaybePromise<void>)
>;

传输(Transport)

¥Transport

自 2.11.0 起可用

¥Available since 2.11.0

transport 钩子允许你跨服务器/客户端边界传输自定义类型。

¥The transport hook allows you to transport custom types across the server/client boundary.

每个传输器都有一对 encodedecode 函数。在服务器上,encode 确定值是否是自定义类型的实例,如果是,则返回值的非假编码,该编码可以是对象或数组(否则为 false)。

¥Each transporter has a pair of encode and decode functions. On the server, encode determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (or false otherwise).

在浏览器中,decode 将编码重新转换为自定义类型的实例。

¥In the browser, decode turns the encoding back into an instance of the custom type.

import type { 
type Transport = {
    [x: string]: Transporter<any, any>;
}

The transport hook allows you to transport custom types across the server/client boundary.

Each transporter has a pair of encode and decode functions. On the server, encode determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (or false otherwise).

In the browser, decode turns the encoding back into an instance of the custom type.

import type { Transport } from '@sveltejs/kit';

declare class MyCustomType {
	data: any
}

// hooks.js
export const transport: Transport = {
	MyCustomType: {
		encode: (value) => value instanceof MyCustomType &#x26;&#x26; [value.data],
		decode: ([data]) => new MyCustomType(data)
	}
};
@since2.11.0
Transport
} from '@sveltejs/kit';
declare class class MyCustomTypeMyCustomType { MyCustomType.data: anydata: any } // hooks.js export const const transport: Transporttransport:
type Transport = {
    [x: string]: Transporter<any, any>;
}

The transport hook allows you to transport custom types across the server/client boundary.

Each transporter has a pair of encode and decode functions. On the server, encode determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (or false otherwise).

In the browser, decode turns the encoding back into an instance of the custom type.

import type { Transport } from '@sveltejs/kit';

declare class MyCustomType {
	data: any
}

// hooks.js
export const transport: Transport = {
	MyCustomType: {
		encode: (value) => value instanceof MyCustomType &#x26;&#x26; [value.data],
		decode: ([data]) => new MyCustomType(data)
	}
};
@since2.11.0
Transport
= {
type MyCustomType: {
    encode: (value: any) => false | any[];
    decode: ([data]: any) => MyCustomType;
}
MyCustomType
: {
Transporter<any, any>.encode: (value: any) => anyencode: (value: anyvalue) => value: anyvalue instanceof class MyCustomTypeMyCustomType && [value: MyCustomTypevalue.MyCustomType.data: anydata], Transporter<any, any>.decode: (data: any) => anydecode: ([data: anydata]) => new constructor MyCustomType(): MyCustomTypeMyCustomType(data: anydata) } };
type Transport = Record<string, Transporter>;

传输器(Transporter)

¥Transporter

transport 钩子的成员。

¥A member of the transport hook.

interface Transporter<
	T = any,
	U = Exclude<
		any,
		false | 0 | '' | null | undefined | typeof NaN
	>
> {}
encode: (value: T) => false | U;
decode: (data: U) => T;

私有类型(Private types)

¥Private types

以下内容由上述公共类型引用,但不能直接导入:

¥The following are referenced by the public types documented above, but cannot be imported directly:

AdapterEntry

interface AdapterEntry {}
id: string;

唯一标识 HTTP 服务(例如无服务器功能)并用于数据去重的字符串。例如,/foo/a-[b]/foo/[c] 是不同的路由,但在 Netlify _redirects 文件中都表示为 /foo/:param,因此它们共享一个 ID

¥A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication. For example, /foo/a-[b] and /foo/[c] are different routes, but would both be represented in a Netlify _redirects file as /foo/:param, so they share an ID

filter(route: RouteDefinition): boolean;

将候选路由与当前路由进行比较以确定是否应将其与当前路由分组的函数。

¥A function that compares the candidate route with the current route to determine if it should be grouped with the current route.

用例:

¥Use cases:

  • 后备页面:/foo/[c]/foo/a-[b] 的后备,/[...catchall] 是所有路由的后备

    ¥Fallback pages: /foo/[c] is a fallback for /foo/a-[b], and /[...catchall] is a fallback for all routes

  • 对共享公共 config 的路由进行分组:/foo 应该部署到边缘,/bar/baz 应该部署到无服务器函数

    ¥Grouping routes that share a common config: /foo should be deployed to the edge, /bar and /baz should be deployed to a serverless function

complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise<void>;

在创建条目后调用的函数。你应该在此处将函数写入文件系统并生成重定向清单。

¥A function that is invoked once the entry has been created. This is where you should write the function to the filesystem and generate redirect manifests.

Csp

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

interface CspDirectives {}
'child-src'?: Csp.Sources;
'default-src'?: Array<Csp.Source | Csp.ActionSource>;
'frame-src'?: Csp.Sources;
'worker-src'?: Csp.Sources;
'connect-src'?: Csp.Sources;
'font-src'?: Csp.Sources;
'img-src'?: Csp.Sources;
'manifest-src'?: Csp.Sources;
'media-src'?: Csp.Sources;
'object-src'?: Csp.Sources;
'prefetch-src'?: Csp.Sources;
'script-src'?: Array<Csp.Source | Csp.ActionSource>;
'script-src-elem'?: Csp.Sources;
'script-src-attr'?: Csp.Sources;
'style-src'?: Array<Csp.Source | Csp.ActionSource>;
'style-src-elem'?: Csp.Sources;
'style-src-attr'?: Csp.Sources;
'base-uri'?: Array<Csp.Source | Csp.ActionSource>;
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'
>;
'form-action'?: Array<Csp.Source | Csp.ActionSource>;
'frame-ancestors'?: Array<Csp.HostSource | Csp.SchemeSource | Csp.FrameSource>;
'navigate-to'?: Array<Csp.Source | Csp.ActionSource>;
'report-uri'?: string[];
'report-to'?: string[];
'require-trusted-types-for'?: Array<'script'>;
'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>;
'upgrade-insecure-requests'?: boolean;
'require-sri-for'?: Array<'script' | 'style' | 'script style'>;
  • 已弃用

    ¥deprecated

'block-all-mixed-content'?: boolean;
  • 已弃用

    ¥deprecated

'plugin-types'?: Array<`${string}/${string}` | 'none'>;
  • 已弃用

    ¥deprecated

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'
>;
  • 已弃用

    ¥deprecated

HttpMethod

type HttpMethod =
	| 'GET'
	| 'HEAD'
	| 'POST'
	| 'PUT'
	| 'DELETE'
	| 'PATCH'
	| 'OPTIONS';

日志器(Logger)

¥Logger

interface Logger {}
(msg: string): void;
success(msg: string): void;
error(msg: string): void;
warn(msg: string): void;
minor(msg: string): void;
info(msg: string): void;

MaybePromise

type MaybePromise<T> = T | Promise<T>;

PrerenderEntryGeneratorMismatchHandler

interface PrerenderEntryGeneratorMismatchHandler {}
(details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void;

PrerenderEntryGeneratorMismatchHandlerValue

type PrerenderEntryGeneratorMismatchHandlerValue =
	| 'fail'
	| 'warn'
	| 'ignore'
	| PrerenderEntryGeneratorMismatchHandler;

PrerenderHttpErrorHandler

interface PrerenderHttpErrorHandler {}
(details: {
status: number;
path: string;
referrer: string | null;
referenceType: 'linked' | 'fetched';
message: string;
}): void;

PrerenderHttpErrorHandlerValue

type PrerenderHttpErrorHandlerValue =
	| 'fail'
	| 'warn'
	| 'ignore'
	| PrerenderHttpErrorHandler;

PrerenderMap

type PrerenderMap = Map<string, PrerenderOption>;

PrerenderMissingIdHandler

interface PrerenderMissingIdHandler {}
(details: { path: string; id: string; referrers: string[]; message: string }): void;

PrerenderMissingIdHandlerValue

type PrerenderMissingIdHandlerValue =
	| 'fail'
	| 'warn'
	| 'ignore'
	| PrerenderMissingIdHandler;

PrerenderOption

type PrerenderOption = boolean | 'auto';

预渲染(Prerendered)

¥Prerendered

interface Prerendered {}
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

¥A map of path to { file } objects, where a path like /foo corresponds to foo.html and a path like /bar/ corresponds to bar/index.html.

assets: Map<
string,
{
	/** The MIME type of the asset */
	type: string;
}
>;

path{ type } 对象的映射。

¥A map of path to { type } objects.

redirects: Map<
string,
{
	status: number;
	location: string;
}
>;

预渲染期间遇到的重定向映射。

¥A map of redirects encountered during prerendering.

paths: string[];

预渲染路径数组(没有尾部斜杠,无论 trailingSlash 配置如何)

¥An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)

RequestOptions

interface RequestOptions {}
getClientAddress(): string;
platform?: App.Platform;

RouteSegment

interface RouteSegment {}
content: string;
dynamic: boolean;
rest: boolean;

TrailingSlash

type TrailingSlash = 'never' | 'always' | 'ignore';
上一页 下一页