`](../svelte/svelte-head). Guidance on how to write descriptive titles and descriptions, along with other suggestions on making content understandable by search engines, can be found on Google's [Lighthouse SEO audits](https://web.dev/lighthouse-seo/) documentation.
### 站点地图(Sitemaps)
¥Sitemaps
[站点地图](https://developers.google.com/search/docs/advanced/sitemaps/build-sitemap) 帮助搜索引擎优先考虑你网站内的页面,特别是当你有大量内容时。你可以使用端点动态创建站点地图:
¥[Sitemaps](https://developers.google.com/search/docs/advanced/sitemaps/build-sitemap) help search engines prioritize pages within your site, particularly when you have a large amount of content. You can create a sitemap dynamically using an endpoint:
```js
/// file: src/routes/sitemap.xml/+server.js
export async function GET() {
return new Response(
`
`.trim(),
{
headers: {
'Content-Type': 'application/xml'
}
}
);
}
```
### AMP
现代 Web 开发的一个不幸现实是,有时需要创建网站的 [加速移动页面 (AMP)](https://amp.dev/) 版本。在 SvelteKit 中,可以通过设置 [`inlineStyleThreshold`](configuration#inlineStyleThreshold) 选项来实现这一点……
¥An unfortunate reality of modern web development is that it is sometimes necessary to create an [Accelerated Mobile Pages (AMP)](https://amp.dev/) version of your site. In SvelteKit this can be done by setting the [`inlineStyleThreshold`](configuration#inlineStyleThreshold) option...
```js
/// file: svelte.config.js
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
// since isn't
// allowed, inline all styles
inlineStyleThreshold: Infinity
}
};
export default config;
```
...在根 `+layout.js`/`+layout.server.js` 中禁用 `csr`...
¥...disabling `csr` in your root `+layout.js`/`+layout.server.js`...
```js
/// file: src/routes/+layout.server.js
export const csr = false;
```
...将 `amp` 添加到你的 `app.html`
¥...adding `amp` to your `app.html`
```html
...
```
...并使用 `transformPageChunk` 以及从 `@sveltejs/amp` 导入的 `transform` 转换 HTML:
¥...and transforming the HTML using `transformPageChunk` along with `transform` imported from `@sveltejs/amp`:
```js
/// file: src/hooks.server.js
import * as amp from '@sveltejs/amp';
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
let buffer = '';
return await resolve(event, {
transformPageChunk: ({ html, done }) => {
buffer += html;
if (done) return amp.transform(buffer);
}
});
}
```
为了防止将页面转换为 amp 后发送任何未使用的 CSS,我们可以使用 [`dropcss`](https://www.npmjs.com/package/dropcss):
¥To prevent shipping any unused CSS as a result of transforming the page to amp, we can use [`dropcss`](https://www.npmjs.com/package/dropcss):
```js
// @filename: ambient.d.ts
declare module 'dropcss';
// @filename: index.js
// ---cut---
/// file: src/hooks.server.js
// @errors: 2307
import * as amp from '@sveltejs/amp';
import dropcss from 'dropcss';
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
let buffer = '';
return await resolve(event, {
transformPageChunk: ({ html, done }) => {
buffer += html;
if (done) {
let css = '';
const markup = amp
.transform(buffer)
.replace('⚡', 'amp') // dropcss can't handle this character
.replace(/`;
});
css = dropcss({ css, html: markup }).css;
return markup.replace('', `${css}`);
}
}
});
}
```
# @sveltejs/kit
```js
// @noErrors
import {
Server,
VERSION,
error,
fail,
invalid,
isActionFailure,
isHttpError,
isRedirect,
isValidationError,
json,
normalizeUrl,
redirect,
text
} from '@sveltejs/kit';
```
## 服务器(Server)
¥Server
```dts
class Server {/*…*/}
```
```dts
constructor(manifest: SSRManifest);
```
```dts
init(options: ServerInitOptions): Promise
;
```
```dts
respond(request: Request, options: RequestOptions): Promise
;
```
## VERSION
```dts
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.
```dts
function error(status: number, body: App.Error): never;
```
```dts
function error(
status: number,
body?: {
message: string;
} extends App.Error
? App.Error | string | undefined
: never
): never;
```
## fail
创建 `ActionFailure` 对象。表单提交失败时调用。
¥Create an `ActionFailure` object. Call when form submission fails.
```dts
function fail(status: number): ActionFailure;
```
```dts
function fail(
status: number,
data: T
): ActionFailure;
```
## invalid
自 2.47.3 版本起可用
¥Available since 2.47.3
使用此方法抛出验证错误,强制表单验证失败。可以与传递给表单操作的 `issue` 结合使用,以创建特定字段的问题。
¥Use this to throw a validation error to imperatively fail form validation.
Can be used in combination with `issue` passed to form actions to create field-specific issues.
```ts
import { invalid } from '@sveltejs/kit';
import { form } from '$app/server';
import { tryLogin } from '$lib/server/auth';
import * as v from 'valibot';
export const login = form(
v.object({ name: v.string(), _password: v.string() }),
async ({ name, _password }) => {
const success = tryLogin(name, _password);
if (!success) {
invalid('Incorrect username or password');
}
// ...
}
);
```
```dts
function invalid(
...issues: (StandardSchemaV1.Issue | string)[]
): never;
```
## isActionFailure
检查这是否是 `fail` 抛出的操作失败。
¥Checks whether this is an action failure thrown by `fail`.
```dts
function isActionFailure(e: unknown): e is ActionFailure;
```
## isHttpError
检查这是否是 `error` 抛出的错误。
¥Checks whether this is an error thrown by `error`.
```dts
function isHttpError(
e: unknown,
status?: T
): e is HttpError_1 & {
status: T extends undefined ? never : T;
};
```
## isRedirect
检查这是否是 `redirect` 抛出的重定向。
¥Checks whether this is a redirect thrown by `redirect`.
```dts
function isRedirect(e: unknown): e is Redirect_1;
```
## isValidationError
自 2.47.3 版本起可用
¥Available since 2.47.3
检查这是否是 `invalid` 抛出的验证错误。
¥Checks whether this is an validation error thrown by `invalid`.
```dts
function isValidationError(e: unknown): e is ActionFailure;
```
## json
从提供的数据创建 JSON `Response` 对象。
¥Create a JSON `Response` object from the supplied data.
```dts
function json(data: any, init?: ResponseInit): 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.
```js
// @errors: 7031
import { normalizeUrl } from '@sveltejs/kit';
const { url, denormalize } = normalizeUrl('/blog/post/__data.json');
console.log(url.pathname); // /blog/post
console.log(denormalize('/blog/post/a')); // /blog/post/a/__data.json
```
```dts
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
[查看所有重定向状态代码](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages)
¥[See all redirect status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages)
```dts
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.
```dts
function text(body: string, init?: ResponseInit): Response;
```
## 操作(Action)
¥Action
`+page.server.js` 中 `export const actions = {...}` 一部分的表单操作方法的形状。有关更多信息,请参阅 [表单操作](/docs/kit/form-actions)。
¥Shape of a form action method that is part of `export const actions = {...}` in `+page.server.js`.
See [form actions](/docs/kit/form-actions) for more information.
```dts
type Action<
Params extends
AppLayoutParams<'/'> = AppLayoutParams<'/'>,
OutputData extends Record
| void = Record<
string,
any
> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: RequestEvent
) => MaybePromise;
```
## ActionFailure
```dts
interface ActionFailure
{/*…*/}
```
```dts
status: number;
```
```dts
[uniqueSymbol]: true;
```
## ActionResult
通过 fetch 调用表单操作时,响应将是这些形状之一。
¥When calling a form action via fetch, the response will be one of these shapes.
```svelte
`
¥`form`: The user submitted a ` `
* `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
```dts
type NavigationType =
| 'enter'
| 'form'
| 'leave'
| 'link'
| 'goto'
| 'popstate';
```
## NumericRange
```dts
type NumericRange<
TStart extends number,
TEnd extends number
> = Exclude, LessThan>;
```
## OnNavigate
传递给 [`onNavigate`](/docs/kit/$app-navigation#onNavigate) 回调的参数。
¥The argument passed to [`onNavigate`](/docs/kit/$app-navigation#onNavigate) callbacks.
```dts
type OnNavigate = Navigation & {
/**
* The type of navigation:
* - `form`: The user submitted a `
`
* - `link`: Navigation was triggered by a link click
* - `goto`: Navigation was triggered by a `goto(...)` call or a redirect
* - `popstate`: Navigation was triggered by back/forward navigation
*/
type: Exclude;
/**
* Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.
*/
willUnload: false;
};
```
## 页面(Page)
¥Page
[`page`](/docs/kit/$app-state#page) 反应对象和 [`$page`](/docs/kit/$app-stores) 存储的形状。
¥The shape of the [`page`](/docs/kit/$app-state#page) reactive object and the [`$page`](/docs/kit/$app-stores) store.
```dts
interface Page<
Params extends
AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}
```
```dts
url: URL & { pathname: ResolvedPathname };
```
当前页面的 URL。
¥The URL of the current page.
```dts
params: Params;
```
当前页面的参数 - 例如,对于像 `/blog/[slug]` 这样的路由,一个 `{ slug: string }` 对象。
¥The parameters of the current page - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object.
```dts
route: {/*…*/}
```
有关当前路由的信息。
¥Info about the current route.
```dts
id: RouteId;
```
当前路由的 ID - 例如,对于 `src/routes/blog/[slug]`,它将是 `/blog/[slug]`。当没有匹配的路由时,它是 `null`。
¥The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`. It is `null` when no route is matched.
```dts
status: number;
```
当前页面的 HTTP 状态代码。
¥HTTP status code of the current page.
```dts
error: App.Error | null;
```
当前页面的错误对象(如果有)。从 `handleError` 钩子填充。
¥The error object of the current page, if any. Filled from the `handleError` hooks.
```dts
data: App.PageData & Record
;
```
当前页面上所有 `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`.
```dts
state: App.PageState;
```
页面状态,可以使用 `$app/navigation` 中的 [`pushState`](/docs/kit/$app-navigation#pushState) 和 [`replaceState`](/docs/kit/$app-navigation#replaceState) 函数进行操作。
¥The page state, which can be manipulated using the [`pushState`](/docs/kit/$app-navigation#pushState) and [`replaceState`](/docs/kit/$app-navigation#replaceState) functions from `$app/navigation`.
```dts
form: any;
```
仅在表单提交后填充。有关更多信息,请参阅 [表单操作](/docs/kit/form-actions)。
¥Filled only after a form submission. See [form actions](/docs/kit/form-actions) for more info.
## ParamMatcher
参数匹配器的形状。有关更多信息,请参阅 [matching](/docs/kit/advanced-routing#Matching)。
¥The shape of a param matcher. See [matching](/docs/kit/advanced-routing#Matching) for more info.
```dts
type ParamMatcher = (param: string) => boolean;
```
## PrerenderOption
```dts
type PrerenderOption = boolean | 'auto';
```
## 重定向(Redirect)
¥Redirect
[`redirect`](/docs/kit/@sveltejs-kit#redirect) 函数返回的对象。
¥The object returned by the [`redirect`](/docs/kit/@sveltejs-kit#redirect) function.
```dts
interface Redirect {/*…*/}
```
```dts
status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;
```
[HTTP 状态代码](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages),在 300-308 范围内。
¥The [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308.
```dts
location: string;
```
重定向到的位置。
¥The location to redirect to.
## RemoteCommand
远程 `command` 函数的返回值。完整文档请参见 [远程函数](/docs/kit/remote-functions#command)。
¥The return value of a remote `command` function. See [Remote functions](/docs/kit/remote-functions#command) for full documentation.
## RemoteForm
远程 `form` 函数的返回值。完整文档请参见 [远程函数](/docs/kit/remote-functions#form)。
¥The return value of a remote `form` function. See [Remote functions](/docs/kit/remote-functions#form) for full documentation.
## RemoteFormField
表单字段访问器类型,提供 name()、value() 和 issues() 方法
¥Form field accessor type that provides name(), value(), and issues() methods
```dts
type RemoteFormField =
RemoteFormFieldMethods & {
/**
* Returns an object that can be spread onto an input element with the correct type attribute,
* aria-invalid attribute if the field is invalid, and appropriate value/checked property getters/setters.
* @example
* ```
svelte * * * *
```
*/
as>(
...args: AsArgs
): InputElementProps;
};
```
## RemoteFormFieldType
```dts
type RemoteFormFieldType = {
[K in keyof InputTypeMap]: T extends InputTypeMap[K]
? K
: never;
}[keyof InputTypeMap];
```
## RemoteFormFieldValue
```dts
type RemoteFormFieldValue =
| string
| string[]
| number
| boolean
| File
| File[];
```
## RemoteFormFields
使用递归类型构建带有代理访问的表单字段结构
¥Recursive type to build form fields structure with proxy access
```dts
type RemoteFormFields =
WillRecurseIndefinitely extends true
? RecursiveFormFields
: NonNullable extends
| string
| number
| boolean
| File
? RemoteFormField>
: T extends string[] | File[]
? RemoteFormField & {
[K in number]: RemoteFormField;
}
: T extends Array
? RemoteFormFieldContainer & {
[K in number]: RemoteFormFields;
}
: RemoteFormFieldContainer & {
[K in keyof T]-?: RemoteFormFields;
};
```
## RemoteFormInput
```dts
interface RemoteFormInput {/*…*/}
```
```dts
[key: string]: MaybeArray
;
```
## RemoteFormIssue
```dts
interface RemoteFormIssue {/*…*/}
```
```dts
message: string;
```
## RemotePrerenderFunction
远程 `prerender` 函数的返回值。完整文档请参见 [远程函数](/docs/kit/remote-functions#prerender)。
¥The return value of a remote `prerender` function. See [Remote functions](/docs/kit/remote-functions#prerender) for full documentation.
```dts
type RemotePrerenderFunction = (
arg: Input
) => RemoteResource;
```
## RemoteQuery
```dts
type RemoteQuery = RemoteResource & {
/**
* On the client, this function will update the value of the query without re-fetching it.
* * On the server, this can be called in the context of a `command` or `form` and the specified data will accompany the action response back to the client.
* This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.
*/
set(value: T): void;
/**
* On the client, this function will re-fetch the query from the server.
* * On the server, this can be called in the context of a `command` or `form` and the refreshed data will accompany the action response back to the client.
* This prevents SvelteKit needing to refresh all queries on the page in a second server round-trip.
*/
refresh(): Promise;
/**
* Temporarily override the value of a query. This is used with the `updates` method of a [command](https://svelte.kfwddq.com/docs/kit/remote-functions#command-Updating-queries) or [enhanced form submission](https://svelte.kfwddq.com/docs/kit/remote-functions#form-enhance) to provide optimistic updates.
* * ```
svelte * * * { * await submit().updates( * todos.withOverride((todos) => [...todos, { text:data.get('text') }]) * );* })}> * * 添加待办事项 * *
¥svelte
*
* * {
* await submit().updates(
* todos.withOverride((todos) => [...todos, { text: data.get('text') }])
* );
* })}>
*
* Add Todo
*
*
```
*/
withOverride(
update: (current: Awaited) => Awaited
): RemoteQueryOverride;
};
```
## RemoteQueryFunction
远程 `query` 函数的返回值。完整文档请参见 [远程函数](/docs/kit/remote-functions#query)。
¥The return value of a remote `query` function. See [Remote functions](/docs/kit/remote-functions#query) for full documentation.
```dts
type RemoteQueryFunction = (
arg: Input
) => RemoteQuery;
```
## RemoteQueryOverride
```dts
interface RemoteQueryOverride {/*…*/}
```
```dts
release(): void;
```
## RemoteResource
```dts
type RemoteResource
= Promise> & {
/** The error in case the query fails. Most often this is a [`HttpError`](https://svelte.kfwddq.com/docs/kit/@sveltejs-kit#HttpError) but it isn't guaranteed to be. */
get error(): any;
/** `true` before the first result is available and during refreshes */
get loading(): boolean;
} & (
| {
/** The current value of the query. Undefined until `ready` is `true` */
get current(): undefined;
ready: false;
}
| {
/** The current value of the query. Undefined until `ready` is `true` */
get current(): Awaited;
ready: true;
}
);
```
## RequestEvent
```dts
interface RequestEvent<
Params extends
AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> {/*…*/}
```
```dts
cookies: Cookies;
```
获取或设置与当前请求相关的 cookie
¥Get or set cookies related to the current request
```dts
fetch: typeof fetch;
```
`fetch` 等同于 [原生 `fetch` Web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch),但具有一些附加功能:
¥`fetch` is equivalent to the [native `fetch` web API](https://developer.mozilla.org/en-US/docs/Web/API/fetch), with a few additional features:
* 它可用于在服务器上发出凭证请求,因为它继承了页面请求的 `cookie` 和 `authorization` 标头。
¥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` 对象的 `text` 和 `json` 方法中被捕获并内联到渲染的 HTML 中。请注意,除非通过 [`filterSerializedResponseHeaders`](/docs/kit/hooks#Server-hooks-handle) 明确包含,否则不会序列化标头
¥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`](/docs/kit/hooks#Server-hooks-handle)
* 在 hydration 期间,将从 HTML 中读取响应,以保证一致性并防止额外的网络请求。
¥During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
你可以了解有关使用 cookie [此处](/docs/kit/load#Cookies) 发出凭证请求的更多信息。
¥You can learn more about making credentialed requests with cookies [here](/docs/kit/load#Cookies).
```dts
getClientAddress: () => string;
```
由适配器设置的客户端 IP 地址。
¥The client's IP address, set by the adapter.
```dts
locals: App.Locals;
```
包含在 [`server handle hook`](/docs/kit/hooks#Server-hooks-handle) 内添加到请求的自定义数据。
¥Contains custom data that was added to the request within the [`server handle hook`](/docs/kit/hooks#Server-hooks-handle).
```dts
params: Params;
```
当前路由的参数 - 例如,对于像 `/blog/[slug]` 这样的路由,一个 `{ slug: string }` 对象。
¥The parameters of the current route - e.g. for a route like `/blog/[slug]`, a `{ slug: string }` object.
```dts
platform: Readonly
| undefined;
```
通过适配器提供的其他数据。
¥Additional data made available through the adapter.
```dts
request: Request;
```
原始请求对象。
¥The original request object.
```dts
route: {/*…*/}
```
有关当前路由的信息。
¥Info about the current route.
```dts
id: RouteId;
```
当前路由的 ID - 例如,对于 `src/routes/blog/[slug]`,它将是 `/blog/[slug]`。当没有匹配的路由时,它是 `null`。
¥The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`. It is `null` when no route is matched.
```dts
setHeaders: (headers: Record
) => 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:
```js
// @errors: 7031
/// file: src/routes/blog/+page.js
export async function load({ fetch, setHeaders }) {
const url = `https://cms.example.com/articles.json`;
const response = await fetch(url);
setHeaders({
age: response.headers.get('age'),
'cache-control': response.headers.get('cache-control')
});
return response.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`](/docs/kit/@sveltejs-kit#Cookies) API。
¥You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](/docs/kit/@sveltejs-kit#Cookies) API instead.
```dts
url: URL;
```
请求的 URL。
¥The requested URL.
```dts
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.
```dts
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.
```dts
tracing: {/*…*/}
```
* 自 v2.31.0 起可用
¥available since v2.31.0
访问 span 进行跟踪。如果未启用跟踪,则这些 span 将不执行任何操作。
¥Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
```dts
enabled: boolean;
```
是否启用跟踪。
¥Whether tracing is enabled.
```dts
root: Span;
```
请求的根 span。此跨度名为 `sveltekit.handle.root`。
¥The root span for the request. This span is named `sveltekit.handle.root`.
```dts
current: Span;
```
与当前 `handle` 钩子、`load` 函数或表单操作关联的跨度。
¥The span associated with the current `handle` hook, `load` function, or form action.
```dts
isRemoteRequest: boolean;
```
如果请求通过远程函数来自客户端,则使用 `true`。在这种情况下,`url` 属性将被剥离与数据请求相关的内部信息。如果区别对你很重要,请改用此属性。
¥`true` if the request comes from the client via a remote function. 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.
## RequestHandler
从 `+server.js` 文件导出的 `(event: RequestEvent) => Response` 函数对应于 HTTP 动词(`GET`、`PUT`、`PATCH` 等)并使用该方法处理请求。
¥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` 作为第一个通用参数,你可以通过使用 [生成的类型](/docs/kit/types#Generated-types) 来跳过它。
¥It receives `Params` as the first generic argument, which you can skip by using [generated types](/docs/kit/types#Generated-types) instead.
```dts
type RequestHandler<
Params extends
AppLayoutParams<'/'> = AppLayoutParams<'/'>,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: RequestEvent
) => MaybePromise;
```
## 重新路由(Reroute)
¥Reroute
自 2.3.0 起可用
¥Available since 2.3.0
[`reroute`](/docs/kit/hooks#Universal-hooks-reroute) 钩子允许你在使用 URL 确定要渲染的路由之前对其进行修改。
¥The [`reroute`](/docs/kit/hooks#Universal-hooks-reroute) hook allows you to modify the URL before it is used to determine which route to render.
```dts
type Reroute = (event: {
url: URL;
fetch: typeof fetch;
}) => MaybePromise;
```
## ResolveOptions
```dts
interface ResolveOptions {/*…*/}
```
```dts
transformPageChunk?: (input: { html: string; done: boolean }) => MaybePromise
;
```
* `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.
```dts
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.
```dts
preload?: (input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }) => boolean;
```
* `input` 文件的类型及其路径
¥`input` the type of the file and its path
确定应将什么添加到 `` 标签以预加载它。默认情况下,`js` 和 `css` 文件将被预加载。
¥Determines what should be added to the `` tag to preload it.
By default, `js` and `css` files will be preloaded.
## RouteDefinition
```dts
interface RouteDefinition
{/*…*/}
```
```dts
api: {
methods: Array
;
};
```
```dts
page: {
methods: Array
>;
};
```
```dts
pattern: RegExp;
```
```dts
prerender: PrerenderOption;
```
```dts
segments: RouteSegment[];
```
```dts
methods: Array
;
```
```dts
config: Config;
```
## SSRManifest
```dts
interface SSRManifest {/*…*/}
```
```dts
appDir: string;
```
```dts
appPath: string;
```
```dts
assets: Set
;
```
来自 `kit.config.files.assets` 和服务工作者(如果有)的静态文件。
¥Static files from `kit.config.files.assets` and the service worker (if any).
```dts
mimeTypes: Record
;
```
```dts
_: {/*…*/}
```
将代码放在靠近使用位置的位置
¥private fields
```dts
client: NonNullable
;
```
```dts
nodes: SSRNodeLoader[];
```
```dts
remotes: Record
Promise>;
```
散列文件名 -> 导入到该文件
¥hashed filename -> import to that file
```dts
routes: SSRRoute[];
```
```dts
prerendered_routes: Set
;
```
```dts
matchers: () => Promise
>;
```
```dts
server_assets: Record
;
```
服务器代码导入的所有资源的 `[file]: size` 映射。
¥A `[file]: size` map of all assets imported by server code.
## ServerInit
自 2.10.0 起可用
¥Available since 2.10.0
在服务器响应其第一个请求之前将调用 [`init`](/docs/kit/hooks#Shared-hooks-init)
¥The [`init`](/docs/kit/hooks#Shared-hooks-init) will be invoked before the server responds to its first request
```dts
type ServerInit = () => MaybePromise;
```
## ServerInitOptions
```dts
interface ServerInitOptions {/*…*/}
```
```dts
env: Record
;
```
环境变量映射。
¥A map of environment variables.
```dts
read?: (file: string) => MaybePromise
;
```
将资源文件名转换为 `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
`PageServerLoad` 和 `LayoutServerLoad` 的通用形式。你应该从 `./$types` 导入这些(参见 [生成的类型](/docs/kit/types#Generated-types)),而不是直接使用 `ServerLoad`。
¥The generic form of `PageServerLoad` and `LayoutServerLoad`. You should import those from `./$types` (see [generated types](/docs/kit/types#Generated-types))
rather than using `ServerLoad` directly.
```dts
type ServerLoad<
Params extends
AppLayoutParams<'/'> = AppLayoutParams<'/'>,
ParentData extends Record
= Record<
string,
any
>,
OutputData extends Record | void = Record<
string,
any
> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: ServerLoadEvent
) => MaybePromise;
```
## ServerLoadEvent
```dts
interface ServerLoadEvent<
Params extends
AppLayoutParams<'/'> = AppLayoutParams<'/'>,
ParentData extends Record
= Record<
string,
any
>,
RouteId extends AppRouteId | null = AppRouteId | null
> extends RequestEvent {/*…*/}
```
```dts
parent: () => Promise
;
```
`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.
```dts
depends: (...deps: string[]) => void;
```
此函数声明 `load` 函数依赖于一个或多个 URL 或自定义标识符,随后可将其与 [`invalidate()`](/docs/kit/$app-navigation#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()`](/docs/kit/$app-navigation#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](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding)。
¥URLs can be absolute or relative to the page being loaded, and must be [encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding).
自定义标识符必须以一个或多个小写字母作为前缀,后跟冒号,以符合 [URI 规范](https://www.rfc-editor.org/rfc/rfc3986.html)。
¥Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the [URI specification](https://www.rfc-editor.org/rfc/rfc3986.html).
以下示例显示如何使用 `depends` 注册对自定义标识符的依赖,该标识符在按钮单击后为 `invalidate`d,从而使 `load` 函数重新运行。
¥The following example shows how to use `depends` to register a dependency on a custom identifier, which is `invalidate`d after a button click, making the `load` function rerun.
```js
// @errors: 7031
/// file: src/routes/+page.js
let count = 0;
export async function load({ depends }) {
depends('increase:count');
return { count: count++ };
}
```
```html
/// file: src/routes/+page.svelte
{data.count}
Increase Count
```
```dts
untrack:
(fn: () => T) => T;
```
使用此功能选择退出回调中同步调用的所有内容的依赖跟踪。示例:
¥Use this function to opt out of dependency tracking for everything that is synchronously called within the callback. Example:
```js
// @errors: 7031
/// file: src/routes/+page.js
export async function load({ untrack, url }) {
// Untrack url.pathname so that path changes don't trigger a rerun
if (untrack(() => url.pathname === '/')) {
return { message: 'Welcome!' };
}
}
```
```dts
tracing: {/*…*/}
```
* 自 v2.31.0 起可用
¥available since v2.31.0
访问 span 进行跟踪。如果未启用跟踪,则这些 span 将不执行任何操作。
¥Access to spans for tracing. If tracing is not enabled, these spans will do nothing.
```dts
enabled: boolean;
```
是否启用跟踪。
¥Whether tracing is enabled.
```dts
root: Span;
```
请求的根 span。此跨度名为 `sveltekit.handle.root`。
¥The root span for the request. This span is named `sveltekit.handle.root`.
```dts
current: Span;
```
与当前服务器 `load` 函数关联的跨度。
¥The span associated with the current server `load` function.
## 快照(Snapshot)
¥Snapshot
从页面或布局组件导出的 `export const snapshot` 类型。
¥The type of `export const snapshot` exported from a page or layout component.
```dts
interface Snapshot
{/*…*/}
```
```dts
capture: () => T;
```
```dts
restore: (snapshot: T) => void;
```
## SubmitFunction
```dts
type SubmitFunction<
Success extends
| Record
| undefined = Record,
Failure extends
| Record
| undefined = Record
> = (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;
/**
* Call this to get the default behavior of a form submission response.
* @param options Set `reset: false` if you don't want the `` 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;
}) => MaybePromise)
>;
```
## 传输(Transport)
¥Transport
自 2.11.0 起可用
¥Available since 2.11.0
[`transport`](/docs/kit/hooks#Universal-hooks-transport) 钩子允许你跨服务器/客户端边界传输自定义类型。
¥The [`transport`](/docs/kit/hooks#Universal-hooks-transport) hook allows you to transport custom types across the server/client boundary.
每个传输器都有一对 `encode` 和 `decode` 函数。在服务器上,`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.
```ts
import type { Transport } from '@sveltejs/kit';
declare class MyCustomType {
data: any
}
// hooks.js
export const transport: Transport = {
MyCustomType: {
encode: (value) => value instanceof MyCustomType && [value.data],
decode: ([data]) => new MyCustomType(data)
}
};
```
```dts
type Transport = Record;
```
## 传输器(Transporter)
¥Transporter
[`transport`](/docs/kit/hooks#Universal-hooks-transport) 钩子的成员。
¥A member of the [`transport`](/docs/kit/hooks#Universal-hooks-transport) hook.
```dts
interface Transporter<
T = any,
U = Exclude<
any,
false | 0 | '' | null | undefined | typeof NaN
>
> {/*…*/}
```
```dts
encode: (value: T) => false | U;
```
```dts
decode: (data: U) => T;
```
## ValidationError
`invalid` 抛出的验证错误。
¥A validation error thrown by `invalid`.
```dts
interface ValidationError {/*…*/}
```
```dts
issues: StandardSchemaV1.Issue[];
```
验证问题
¥The validation issues
## 私有类型(Private types)
¥Private types
以下内容由上述公共类型引用,但不能直接导入:
¥The following are referenced by the public types documented above, but cannot be imported directly:
## AdapterEntry
```dts
interface AdapterEntry {/*…*/}
```
```dts
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
```dts
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
```dts
complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise
;
```
在创建条目后调用的函数。你应该在此处将函数写入文件系统并生成重定向清单。
¥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
```dts
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
```dts
interface CspDirectives {/*…*/}
```
```dts
'child-src'?: Csp.Sources;
```
```dts
'default-src'?: Array
;
```
```dts
'frame-src'?: Csp.Sources;
```
```dts
'worker-src'?: Csp.Sources;
```
```dts
'connect-src'?: Csp.Sources;
```
```dts
'font-src'?: Csp.Sources;
```
```dts
'img-src'?: Csp.Sources;
```
```dts
'manifest-src'?: Csp.Sources;
```
```dts
'media-src'?: Csp.Sources;
```
```dts
'object-src'?: Csp.Sources;
```
```dts
'prefetch-src'?: Csp.Sources;
```
```dts
'script-src'?: Array
;
```
```dts
'script-src-elem'?: Csp.Sources;
```
```dts
'script-src-attr'?: Csp.Sources;
```
```dts
'style-src'?: Array
;
```
```dts
'style-src-elem'?: Csp.Sources;
```
```dts
'style-src-attr'?: Csp.Sources;
```
```dts
'base-uri'?: Array
;
```
```dts
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'
>;
```
```dts
'form-action'?: Array
;
```
```dts
'frame-ancestors'?: Array
;
```
```dts
'navigate-to'?: Array
;
```
```dts
'report-uri'?: string[];
```
```dts
'report-to'?: string[];
```
```dts
'require-trusted-types-for'?: Array<'script'>;
```
```dts
'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>;
```
```dts
'upgrade-insecure-requests'?: boolean;
```
```dts
'require-sri-for'?: Array<'script' | 'style' | 'script style'>;
```
```dts
'block-all-mixed-content'?: boolean;
```
```dts
'plugin-types'?: Array<`${string}/${string}` | 'none'>;
```
```dts
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'
>;
```
## HttpMethod
```dts
type HttpMethod =
| 'GET'
| 'HEAD'
| 'POST'
| 'PUT'
| 'DELETE'
| 'PATCH'
| 'OPTIONS';
```
## 日志器(Logger)
¥Logger
```dts
interface Logger {/*…*/}
```
```dts
(msg: string): void;
```
```dts
success(msg: string): void;
```
```dts
error(msg: string): void;
```
```dts
warn(msg: string): void;
```
```dts
minor(msg: string): void;
```
```dts
info(msg: string): void;
```
## MaybePromise
```dts
type MaybePromise = T | Promise;
```
## PrerenderEntryGeneratorMismatchHandler
```dts
interface PrerenderEntryGeneratorMismatchHandler {/*…*/}
```
```dts
(details: { generatedFromId: string; entry: string; matchedId: string; message: string }): void;
```
## PrerenderEntryGeneratorMismatchHandlerValue
```dts
type PrerenderEntryGeneratorMismatchHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderEntryGeneratorMismatchHandler;
```
## PrerenderHttpErrorHandler
```dts
interface PrerenderHttpErrorHandler {/*…*/}
```
```dts
(details: {
status: number;
path: string;
referrer: string | null;
referenceType: 'linked' | 'fetched';
message: string;
}): void;
```
## PrerenderHttpErrorHandlerValue
```dts
type PrerenderHttpErrorHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderHttpErrorHandler;
```
## PrerenderMap
```dts
type PrerenderMap = Map;
```
## PrerenderMissingIdHandler
```dts
interface PrerenderMissingIdHandler {/*…*/}
```
```dts
(details: { path: string; id: string; referrers: string[]; message: string }): void;
```
## PrerenderMissingIdHandlerValue
```dts
type PrerenderMissingIdHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderMissingIdHandler;
```
## PrerenderOption
```dts
type PrerenderOption = boolean | 'auto';
```
## PrerenderUnseenRoutesHandler
```dts
interface PrerenderUnseenRoutesHandler {/*…*/}
```
```dts
(details: { routes: string[]; message: string }): void;
```
## PrerenderUnseenRoutesHandlerValue
```dts
type PrerenderUnseenRoutesHandlerValue =
| 'fail'
| 'warn'
| 'ignore'
| PrerenderUnseenRoutesHandler;
```
## 预渲染(Prerendered)
¥Prerendered
```dts
interface Prerendered {/*…*/}
```
```dts
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`.
```dts
assets: Map<
string,
{
/** The MIME type of the asset */
type: string;
}
>;
```
`path` 到 `{ type }` 对象的映射。
¥A map of `path` to `{ type }` objects.
```dts
redirects: Map<
string,
{
status: number;
location: string;
}
>;
```
预渲染期间遇到的重定向映射。
¥A map of redirects encountered during prerendering.
```dts
paths: string[];
```
预渲染路径数组(没有尾部斜杠,无论 trailingSlash 配置如何)
¥An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)
## RequestOptions
```dts
interface RequestOptions {/*…*/}
```
```dts
getClientAddress(): string;
```
```dts
platform?: App.Platform;
```
## RouteSegment
```dts
interface RouteSegment {/*…*/}
```
```dts
content: string;
```
```dts
dynamic: boolean;
```
```dts
rest: boolean;
```
## TrailingSlash
```dts
type TrailingSlash = 'never' | 'always' | 'ignore';
```
# @sveltejs/kit/hooks
```js
// @noErrors
import { sequence } from '@sveltejs/kit/hooks';
```
## sequence
用于以类似中间件的方式对多个 `handle` 调用进行排序的辅助函数。`handle` 选项的行为如下:
¥A helper function for sequencing multiple `handle` calls in a middleware-like manner.
The behavior for the `handle` options is as follows:
* `transformPageChunk` 按反向顺序应用并合并
¥`transformPageChunk` is applied in reverse order and merged
* `preload` 按正向顺序应用,第一个选项 "wins" 和其后的任何 `preload` 选项都被调用
¥`preload` is applied in forward order, the first option "wins" and no `preload` options after it are called
* `filterSerializedResponseHeaders` 的行为与 `preload` 相同
¥`filterSerializedResponseHeaders` behaves the same as `preload`
```js
// @errors: 7031
/// file: src/hooks.server.js
import { sequence } from '@sveltejs/kit/hooks';
/** @type {import('@sveltejs/kit').Handle} */
async function first({ event, resolve }) {
console.log('first pre-processing');
const result = await resolve(event, {
transformPageChunk: ({ html }) => {
// transforms are applied in reverse order
console.log('first transform');
return html;
},
preload: () => {
// this one wins as it's the first defined in the chain
console.log('first preload');
return true;
}
});
console.log('first post-processing');
return result;
}
/** @type {import('@sveltejs/kit').Handle} */
async function second({ event, resolve }) {
console.log('second pre-processing');
const result = await resolve(event, {
transformPageChunk: ({ html }) => {
console.log('second transform');
return html;
},
preload: () => {
console.log('second preload');
return true;
},
filterSerializedResponseHeaders: () => {
// this one wins as it's the first defined in the chain
console.log('second filterSerializedResponseHeaders');
return true;
}
});
console.log('second post-processing');
return result;
}
export const handle = sequence(first, second);
```
上面的示例将打印:
¥The example above would print:
```
first pre-processing
first preload
second pre-processing
second filterSerializedResponseHeaders
second transform
first transform
second post-processing
first post-processing
```
```dts
function sequence(...handlers: Handle[]): Handle;
```
# @sveltejs/kit/node/polyfills
```js
// @noErrors
import { installPolyfills } from '@sveltejs/kit/node/polyfills';
```
## installPolyfills
使各种 Web API 可用作全局变量:
¥Make various web APIs available as globals:
* `crypto`
* `File`
```dts
function installPolyfills(): void;
```
# @sveltejs/kit/node
```js
// @noErrors
import {
createReadableStream,
getRequest,
setResponse
} from '@sveltejs/kit/node';
```
## createReadableStream
自 2.4.0 起可用
¥Available since 2.4.0
将磁盘上的文件转换为可读流
¥Converts a file on disk to a readable stream
```dts
function createReadableStream(file: string): ReadableStream;
```
## getRequest
```dts
function getRequest({
request,
base,
bodySizeLimit
}: {
request: import('http').IncomingMessage;
base: string;
bodySizeLimit?: number;
}): Promise;
```
## setResponse
```dts
function setResponse(
res: import('http').ServerResponse,
response: Response
): Promise;
```
# @sveltejs/kit/vite
```js
// @noErrors
import { sveltekit } from '@sveltejs/kit/vite';
```
## sveltekit
返回 SvelteKit Vite 插件。
¥Returns the SvelteKit Vite plugins.
```dts
function sveltekit(): Promise;
```
# $app/environment
```js
// @noErrors
import { browser, building, dev, version } from '$app/environment';
```
## browser
如果应用在浏览器中运行,则为 `true`。
¥`true` if the app is running in the browser.
```dts
const browser: boolean;
```
## building
SvelteKit 在 `build` 步骤中通过运行应用来分析你的应用。在此过程中,`building` 是 `true`。这也适用于预渲染期间。
¥SvelteKit analyses your app during the `build` step by running it. During this process, `building` is `true`. This also applies during prerendering.
```dts
const building: boolean;
```
## dev
开发服务器是否正在运行。这不能保证与 `NODE_ENV` 或 `MODE` 相对应。
¥Whether the dev server is running. This is not guaranteed to correspond to `NODE_ENV` or `MODE`.
```dts
const dev: boolean;
```
## version
`config.kit.version.name` 的值。
¥The value of `config.kit.version.name`.
```dts
const version: string;
```
# $app/forms
```js
// @noErrors
import { applyAction, deserialize, enhance } from '$app/forms';
```
## applyAction
此操作使用给定的数据更新当前页面的 `form` 属性并更新 `page.status`。如果出现错误,它会重定向到最近的错误页面。
¥This action updates the `form` property of the current page with the given data and updates `page.status`.
In case of an error, it redirects to the nearest error page.
```dts
function applyAction<
Success extends Record | undefined,
Failure extends Record | undefined
>(
result: import('@sveltejs/kit').ActionResult<
Success,
Failure
>
): Promise;
```
## deserialize
使用此函数反序列化表单提交的响应。用法:
¥Use this function to deserialize the response from a form submission.
Usage:
```js
// @errors: 7031
import { deserialize } from '$app/forms';
async function handleSubmit(event) {
const response = await fetch('/form?/action', {
method: 'POST',
body: new FormData(event.target)
});
const result = deserialize(await response.text());
// ...
}
```
```dts
function deserialize<
Success extends Record | undefined,
Failure extends Record | undefined
>(
result: string
): import('@sveltejs/kit').ActionResult;
```
## enhance
此操作增强了 `` 元素的功能,该元素无需 JavaScript 即可正常工作。
¥This action enhances a ` ` element that otherwise would work without JavaScript.
提交时,使用给定的 FormData 和应触发的 `action` 调用 `submit` 函数。如果调用 `cancel`,则表单将不会提交。你可以使用 abort `controller` 取消提交,以防另一个提交开始。如果返回一个函数,则会使用服务器的响应来调用该函数。如果没有返回任何内容,则将使用回退策略。
¥The `submit` function is called upon submission with the given FormData and the `action` that should be triggered.
If `cancel` is called, the form will not be submitted.
You can use the abort `controller` to cancel the submission in case another one starts.
If a function is returned, that function is called with the response from the server.
If nothing is returned, the fallback will be used.
如果此函数或其返回值未设置,则
¥If this function or its return value isn't set, it
* 如果操作与表单位于同一页面,则回退到使用返回数据更新 `form` 属性。
¥falls back to updating the `form` prop with the returned data if the action is on the same page as the form
* 更新 `page.status`
¥updates `page.status`
* 如果提交成功且没有重定向响应,则重置 ` ` 元素并使所有数据无效。
¥resets the ` ` element and invalidates all data in case of successful submission with no redirect response
* 如果出现重定向响应,则重定向。
¥redirects in case of a redirect response
* 如果出现意外错误,则重定向到最近的错误页面。
¥redirects to the nearest error page in case of an unexpected error
如果你提供了一个带有回调的自定义函数,并且想要使用默认行为,请在回调中调用 `update`。它接受一个选项对象。
¥If you provide a custom function with a callback and want to use the default behavior, invoke `update` in your callback.
It accepts an options object
* 如果你不希望 ` ` 值在提交成功后被重置,请使用 `reset: false`
¥`reset: false` if you don't want the ` ` values to be reset after a successful submission
* 如果你不希望操作在提交后调用 `invalidateAll`,请使用 `invalidateAll: false`
¥`invalidateAll: false` if you don't want the action to call `invalidateAll` after submission
```dts
function enhance<
Success extends Record | undefined,
Failure extends Record | undefined
>(
form_element: HTMLFormElement,
submit?: import('@sveltejs/kit').SubmitFunction<
Success,
Failure
>
): {
destroy(): void;
};
```
# $app/navigation
```js
// @noErrors
import {
afterNavigate,
beforeNavigate,
disableScrollHandling,
goto,
invalidate,
invalidateAll,
onNavigate,
preloadCode,
preloadData,
pushState,
refreshAll,
replaceState
} from '$app/navigation';
```
## afterNavigate
当前组件挂载时以及我们导航到 URL 时运行提供的 `callback` 的生命周期函数。
¥A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a URL.
必须在组件初始化期间调用 `afterNavigate`。只要组件已安装,它就会保持活动状态。
¥`afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted.
```dts
function afterNavigate(
callback: (
navigation: import('@sveltejs/kit').AfterNavigate
) => void
): void;
```
## beforeNavigate
在我们导航到 URL 之前触发的导航拦截器,无论是通过单击链接、调用 `goto(...)` 还是使用浏览器的后退/前进控件。
¥A navigation interceptor that triggers before we navigate to a URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls.
调用 `cancel()` 将阻止导航完成。如果 `navigation.type === 'leave'` — 意味着用户正在离开应用(或关闭选项卡) — 调用 `cancel` 将触发原生浏览器卸载确认对话框。在这种情况下,导航可能会或可能不会被取消,具体取决于用户的响应。
¥Calling `cancel()` will prevent the navigation from completing. If `navigation.type === 'leave'` — meaning the user is navigating away from the app (or closing the tab) — calling `cancel` will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user's response.
当导航不指向 SvelteKit 拥有的路由(因此由 SvelteKit 的客户端路由控制)时,`navigation.to.route.id` 将为 `null`。
¥When a navigation isn't to a SvelteKit-owned route (and therefore controlled by SvelteKit's client-side router), `navigation.to.route.id` will be `null`.
如果导航(如果没有取消)会导致文档卸载 — 换句话说,`'leave'` 导航和 `'link'` 导航,其中 `navigation.to.route === null` — `navigation.willUnload` 是 `true`。
¥If the navigation will (if not cancelled) cause the document to unload — in other words `'leave'` navigations and `'link'` navigations where `navigation.to.route === null` — `navigation.willUnload` is `true`.
必须在组件初始化期间调用 `beforeNavigate`。只要组件已安装,它就会保持活动状态。
¥`beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted.
```dts
function beforeNavigate(
callback: (
navigation: import('@sveltejs/kit').BeforeNavigate
) => void
): void;
```
## disableScrollHandling
如果在导航(例如,在 `onMount` 或 `afterNavigate` 或操作中)之后更新页面时调用,则会禁用 SvelteKit 的内置滚动处理。通常不鼓励这样做,因为它打破了用户的期望。
¥If called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling.
This is generally discouraged, since it breaks user expectations.
```dts
function disableScrollHandling(): void;
```
## goto
允许你以编程方式导航到给定的路由,并提供诸如保持当前元素聚焦等选项。返回一个 Promise,当 SvelteKit 导航(或导航失败,在这种情况下 promise 被拒绝)到指定的 `url` 时解析。
¥Allows you to navigate programmatically to a given route, with options such as keeping the current element focused.
Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `url`.
对于外部 URL,请使用 `window.location = url`,而不是调用 `goto(url)`。
¥For external URLs, use `window.location = url` instead of calling `goto(url)`.
```dts
function goto(
url: string | URL,
opts?: {
replaceState?: boolean | undefined;
noScroll?: boolean | undefined;
keepFocus?: boolean | undefined;
invalidateAll?: boolean | undefined;
invalidate?:
| (string | URL | ((url: URL) => boolean))[]
| undefined;
state?: App.PageState | undefined;
}
): Promise;
```
## invalidate
如果任何属于当前活动页面的 `load` 函数依赖于相关 `url`,则通过 `fetch` 或 `depends` 重新运行。返回页面随后更新时解析的 `Promise`。
¥Causes any `load` functions belonging to the currently active page to re-run if they depend on the `url` in question, via `fetch` or `depends`. Returns a `Promise` that resolves when the page is subsequently updated.
如果参数作为 `string` 或 `URL` 给出,它必须解析为传递给 `fetch` 或 `depends`(包括查询参数)的相同 URL。要创建自定义标识符,请使用以 `[a-z]+:` 开头的字符串(例如 `custom:state`) - 这是一个有效的 URL。
¥If the argument is given as a `string` or `URL`, it must resolve to the same URL that was passed to `fetch` or `depends` (including query parameters).
To create a custom identifier, use a string beginning with `[a-z]+:` (e.g. `custom:state`) — this is a valid URL.
`function` 参数可用于定义自定义谓词。它接收完整的 `URL`,并在返回 `true` 时导致 `load` 重新运行。如果你想根据模式而不是完全匹配使无效,这将很有用。
¥The `function` argument can be used define a custom predicate. It receives the full `URL` and causes `load` to rerun if `true` is returned.
This can be useful if you want to invalidate based on a pattern instead of a exact match.
```ts
// Example: Match '/path' regardless of the query parameters
import { invalidate } from '$app/navigation';
invalidate((url) => url.pathname === '/path');
```
```dts
function invalidate(
resource: string | URL | ((url: URL) => boolean)
): Promise;
```
## invalidateAll
导致所有属于当前活动页面的 `load` 函数重新运行。返回页面随后更新时解析的 `Promise`。
¥Causes all `load` functions belonging to the currently active page to re-run. Returns a `Promise` that resolves when the page is subsequently updated.
```dts
function invalidateAll(): Promise;
```
## onNavigate
在我们导航到新 URL 之前立即运行提供的 `callback` 的生命周期函数(全页导航除外)。
¥A lifecycle function that runs the supplied `callback` immediately before we navigate to a new URL except during full-page navigations.
如果你返回 `Promise`,SvelteKit 将等待它解析后再完成导航。这允许你(例如)使用 `document.startViewTransition`。避免解决速度慢的 promise,因为导航在用户看来会停滞不前。
¥If you return a `Promise`, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use `document.startViewTransition`. Avoid promises that are slow to resolve, since navigation will appear stalled to the user.
如果回调返回一个函数(或解析为函数的 `Promise`),则 DOM 更新后将调用该函数。
¥If a function (or a `Promise` that resolves to a function) is returned from the callback, it will be called once the DOM has updated.
必须在组件初始化期间调用 `onNavigate`。只要组件已安装,它就会保持活动状态。
¥`onNavigate` must be called during a component initialization. It remains active as long as the component is mounted.
```dts
function onNavigate(
callback: (
navigation: import('@sveltejs/kit').OnNavigate
) => MaybePromise<(() => void) | void>
): void;
```
## preloadCode
以编程方式导入尚未获取的路由的代码。通常,你可能会调用它来加快后续导航速度。
¥Programmatically imports the code for routes that haven't yet been fetched.
Typically, you might call this to speed up subsequent navigation.
你可以通过任何匹配的路径名指定路由,例如 `/about`(匹配 `src/routes/about/+page.svelte`)或 `/blog/*`(匹配 `src/routes/blog/[slug]/+page.svelte`)。
¥You can specify routes by any matching pathname such as `/about` (to match `src/routes/about/+page.svelte`) or `/blog/*` (to match `src/routes/blog/[slug]/+page.svelte`).
与 `preloadData` 不同,这不会调用 `load` 函数。返回一个 Promise,当模块被导入时解析。
¥Unlike `preloadData`, this won't call `load` functions.
Returns a Promise that resolves when the modules have been imported.
```dts
function preloadCode(pathname: string): Promise;
```
## preloadData
以编程方式预加载给定的页面,这意味着
¥Programmatically preloads the given page, which means
1. 确保页面的代码已加载,并且
¥ensuring that the code for the page is loaded, and
2. 使用适当的选项调用页面的加载函数。
¥calling the page's load function with the appropriate options.
当用户点击或将鼠标悬停在带有 `data-sveltekit-preload-data` 的 `` 元素上时,SvelteKit 会触发相同的行为。如果下一个导航是 `href`,则将使用从加载返回的值,使导航即时完成。返回一个 Promise,该 Promise 在预加载完成后通过运行新路由的 `load` 函数的结果解析。
¥This is the same behaviour that SvelteKit triggers when the user taps or mouses over an ` ` element with `data-sveltekit-preload-data`.
If the next navigation is to `href`, the values returned from load will be used, making navigation instantaneous.
Returns a Promise that resolves with the result of running the new route's `load` functions once the preload is complete.
```dts
function preloadData(href: string): Promise<
| {
type: 'loaded';
status: number;
data: Record;
}
| {
type: 'redirect';
location: string;
}
>;
```
## pushState
以编程方式使用给定的 `page.state` 创建新的历史记录条目。要使用当前 URL,你可以将 `''` 作为第一个参数传递。用于 [浅路由](/docs/kit/shallow-routing)。
¥Programmatically create a new history entry with the given `page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](/docs/kit/shallow-routing).
```dts
function pushState(
url: string | URL,
state: App.PageState
): void;
```
## refreshAll
导致所有当前活动的远程函数刷新,并重新运行属于当前活动页面的所有 `load` 函数(除非通过选项参数禁用)。返回页面随后更新时解析的 `Promise`。
¥Causes all currently active remote functions to refresh, and all `load` functions belonging to the currently active page to re-run (unless disabled via the option argument).
Returns a `Promise` that resolves when the page is subsequently updated.
```dts
function refreshAll({
includeLoadFunctions
}?: {
includeLoadFunctions?: boolean;
}): Promise;
```
## replaceState
以编程方式用给定的 `page.state` 替换当前历史记录条目。要使用当前 URL,你可以将 `''` 作为第一个参数传递。用于 [浅路由](/docs/kit/shallow-routing)。
¥Programmatically replace the current history entry with the given `page.state`. To use the current URL, you can pass `''` as the first argument. Used for [shallow routing](/docs/kit/shallow-routing).
```dts
function replaceState(
url: string | URL,
state: App.PageState
): void;
```
# $app/paths
```js
// @noErrors
import { asset, assets, base, resolve, resolveRoute } from '$app/paths';
```
## asset
自 2.26 起可用
¥Available since 2.26
解析 `static` 目录中资源的 URL,如果已配置,则通过在其前添加 [`config.kit.paths.assets`](/docs/kit/configuration#paths) 前缀,否则通过在其前添加基本路径前缀。
¥Resolve the URL of an asset in your `static` directory, by prefixing it with [`config.kit.paths.assets`](/docs/kit/configuration#paths) if configured, or otherwise by prefixing it with the base path.
在服务器渲染期间,基本路径是相对的,并且取决于当前正在渲染的页面。
¥During server rendering, the base path is relative and depends on the page currently being rendered.
```svelte
```
```dts
function asset(file: Asset): string;
```
## assets
改用 [`asset(...)`](/docs/kit/$app-paths#asset)
¥Use [`asset(...)`](/docs/kit/$app-paths#asset) instead
与 [`config.kit.paths.assets`](/docs/kit/configuration#paths) 匹配的绝对路径。
¥An absolute path that matches [`config.kit.paths.assets`](/docs/kit/configuration#paths).
```dts
let assets:
| ''
| `https://${string}`
| `http://${string}`
| '/_svelte_kit_assets';
```
## base
改用 [`resolve(...)`](/docs/kit/$app-paths#resolve)
¥Use [`resolve(...)`](/docs/kit/$app-paths#resolve) instead
与 [`config.kit.paths.base`](/docs/kit/configuration#paths) 匹配的字符串。
¥A string that matches [`config.kit.paths.base`](/docs/kit/configuration#paths).
示例用法:` Link `
¥Example usage: `Link `
```dts
let base: '' | `/${string}`;
```
## resolve
自 2.26 起可用
¥Available since 2.26
通过在路径名前添加基本路径(如果有)来解析路径名,或者通过在动态段中填充参数来解析路由 ID。
¥Resolve a pathname by prefixing it with the base path, if any, or resolve a route ID by populating dynamic segments with parameters.
在服务器渲染期间,基本路径是相对的,并且取决于当前正在渲染的页面。
¥During server rendering, the base path is relative and depends on the page currently being rendered.
```js
// @errors: 7031
import { resolve } from '$app/paths';
// using a pathname
const resolved = resolve(`/blog/hello-world`);
// using a route ID plus parameters
const resolved = resolve('/blog/[slug]', {
slug: 'hello-world'
});
```
```dts
function resolve(
...args: ResolveArgs
): ResolvedPathname;
```
## resolveRoute
改用 [`resolve(...)`](/docs/kit/$app-paths#resolve)
¥Use [`resolve(...)`](/docs/kit/$app-paths#resolve) instead
```dts
function resolveRoute(
...args: ResolveArgs
): ResolvedPathname;
```
# $app/server
```js
// @noErrors
import {
command,
form,
getRequestEvent,
prerender,
query,
read
} from '$app/server';
```
## command
自 2.27 起可用
¥Available since 2.27
创建远程命令。从浏览器调用时,该函数将通过 `fetch` 调用在服务器上执行。
¥Creates a remote command. When called from the browser, the function will be invoked on the server via a `fetch` call.
完整文档请参见 [远程函数](/docs/kit/remote-functions#command)。
¥See [Remote functions](/docs/kit/remote-functions#command) for full documentation.
```dts
function command(
fn: () => Output
): RemoteCommand;
```
```dts
function command (
validate: 'unchecked',
fn: (arg: Input) => Output
): RemoteCommand ;
```
```dts
function command(
validate: Schema,
fn: (arg: StandardSchemaV1.InferOutput) => Output
): RemoteCommand<
StandardSchemaV1.InferInput,
Output
>;
```
## form
自 2.27 起可用
¥Available since 2.27
创建一个可展开到 ` ` 元素上的表单对象。
¥Creates a form object that can be spread onto a ` ` element.
完整文档请参见 [远程函数](/docs/kit/remote-functions#form)。
¥See [Remote functions](/docs/kit/remote-functions#form) for full documentation.
```dts
function form(
fn: () => MaybePromise
): RemoteForm;
```
```dts
function form (
validate: 'unchecked',
fn: (
data: Input,
issue: InvalidField
) => MaybePromise
): RemoteForm ;
```
```dts
function form<
Schema extends StandardSchemaV1<
RemoteFormInput,
Record
>,
Output
>(
validate: Schema,
fn: (
data: StandardSchemaV1.InferOutput,
issue: InvalidField>
) => MaybePromise
): RemoteForm, Output>;
```
## getRequestEvent
自可用以来 2.20.0
¥Available since 2.20.0
返回当前 `RequestEvent`。可在服务器钩子、服务器 `load` 函数、操作和端点(以及它们调用的函数)中使用。
¥Returns the current `RequestEvent`. Can be used inside server hooks, server `load` functions, actions, and endpoints (and functions called by them).
在没有 [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) 的环境中,必须同步调用此函数(即不在 `await` 之后)。
¥In environments without [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage), this must be called synchronously (i.e. not after an `await`).
```dts
function getRequestEvent(): RequestEvent;
```
## prerender
自 2.27 起可用
¥Available since 2.27
创建一个远程预渲染函数。从浏览器调用时,该函数将通过 `fetch` 调用在服务器上执行。
¥Creates a remote prerender function. When called from the browser, the function will be invoked on the server via a `fetch` call.
完整文档请参见 [远程函数](/docs/kit/remote-functions#prerender)。
¥See [Remote functions](/docs/kit/remote-functions#prerender) for full documentation.
```dts
function prerender(
fn: () => MaybePromise,
options?:
| {
inputs?: RemotePrerenderInputsGenerator;
dynamic?: boolean;
}
| undefined
): RemotePrerenderFunction;
```
```dts
function prerender (
validate: 'unchecked',
fn: (arg: Input) => MaybePromise,
options?:
| {
inputs?: RemotePrerenderInputsGenerator ;
dynamic?: boolean;
}
| undefined
): RemotePrerenderFunction ;
```
```dts
function prerender(
schema: Schema,
fn: (
arg: StandardSchemaV1.InferOutput
) => MaybePromise,
options?:
| {
inputs?: RemotePrerenderInputsGenerator<
StandardSchemaV1.InferInput
>;
dynamic?: boolean;
}
| undefined
): RemotePrerenderFunction<
StandardSchemaV1.InferInput,
Output
>;
```
## query
自 2.27 起可用
¥Available since 2.27
创建远程查询。从浏览器调用时,该函数将通过 `fetch` 调用在服务器上执行。
¥Creates a remote query. When called from the browser, the function will be invoked on the server via a `fetch` call.
完整文档请参见 [远程函数](/docs/kit/remote-functions#query)。
¥See [Remote functions](/docs/kit/remote-functions#query) for full documentation.
```dts
function query(
fn: () => MaybePromise
): RemoteQueryFunction;
```
```dts
function query (
validate: 'unchecked',
fn: (arg: Input) => MaybePromise
): RemoteQueryFunction ;
```
```dts
function query(
schema: Schema,
fn: (
arg: StandardSchemaV1.InferOutput
) => MaybePromise
): RemoteQueryFunction<
StandardSchemaV1.InferInput,
Output
>;
```
## read
自 2.4.0 起可用
¥Available since 2.4.0
从文件系统读取导入资源的内容。
¥Read the contents of an imported asset from the filesystem
```js
// @errors: 7031
import { read } from '$app/server';
import somefile from './somefile.txt';
const asset = read(somefile);
const text = await asset.text();
```
```dts
function read(asset: string): Response;
```
## query
```dts
namespace query {
/**
* Creates a batch query function that collects multiple calls and executes them in a single request
* * See [Remote functions](https://svelte.kfwddq.com/docs/kit/remote-functions#query.batch) for full documentation.
* * @since 2.35
*/
function batch (
validate: 'unchecked',
fn: (
args: Input[]
) => MaybePromise<(arg: Input, idx: number) => Output>
): RemoteQueryFunction ;
/**
* Creates a batch query function that collects multiple calls and executes them in a single request
* * See [Remote functions](https://svelte.kfwddq.com/docs/kit/remote-functions#query.batch) for full documentation.
* * @since 2.35
*/
function batch(
schema: Schema,
fn: (
args: StandardSchemaV1.InferOutput[]
) => MaybePromise<
(
arg: StandardSchemaV1.InferOutput,
idx: number
) => Output
>
): RemoteQueryFunction<
StandardSchemaV1.InferInput,
Output
>;
}
```
# $app/state
SvelteKit 通过 `$app/state` 模块提供三个只读状态对象 - `page`、`navigating` 和 `updated`。
¥SvelteKit makes three read-only state objects available via the `$app/state` module — `page`, `navigating` and `updated`.
> 此模块已添加到 2.12 版本。如果你使用的是早期版本的 SvelteKit,请改用 [`$app/stores`]($app-stores)。
```js
// @noErrors
import { navigating, page, updated } from '$app/state';
```
## navigating
表示正在进行的导航的只读对象,具有 `from`、`to`、`type` 和(如果是 `type === 'popstate'`)`delta` 属性。当没有导航发生时或在服务器渲染期间,值为 `null`。
¥A read-only object representing an in-progress navigation, with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties.
Values are `null` when no navigation is occurring, or during server rendering.
```dts
const navigating:
| import('@sveltejs/kit').Navigation
| {
from: null;
to: null;
type: null;
willUnload: null;
delta: null;
complete: null;
};
```
## page
包含当前页面信息的只读反应对象,可用于多种用例:
¥A read-only reactive object with information about the current page, serving several use cases:
* 检索组件树中任何位置的所有页面/布局的组合 `data`(另请参阅 [加载数据](/docs/kit/load))
¥retrieving the combined `data` of all pages/layouts anywhere in your component tree (also see [loading data](/docs/kit/load))
* 检索组件树中任何位置的 `form` prop 的当前值(另请参阅 [表单操作](/docs/kit/form-actions))
¥retrieving the current value of the `form` prop anywhere in your component tree (also see [form actions](/docs/kit/form-actions))
* 检索通过 `goto`、`pushState` 或 `replaceState` 设置的页面状态(另请参阅 [goto](/docs/kit/$app-navigation#goto) 和 [浅路由](/docs/kit/shallow-routing))
¥retrieving the page state that was set through `goto`, `pushState` or `replaceState` (also see [goto](/docs/kit/$app-navigation#goto) and [shallow routing](/docs/kit/shallow-routing))
* 检索元数据,例如你所在的 URL、当前路由及其参数,以及是否存在错误
¥retrieving metadata such as the URL you're on, the current route and its parameters, and whether or not there was an error
```svelte
Currently at {page.url.pathname}
{#if page.error}
Problem detected
{:else}
All systems operational
{/if}
```
`page` 的更改仅通过 Runes 提供。(旧版反应性语法不会反映任何更改)
¥Changes to `page` are available exclusively with runes. (The legacy reactivity syntax will not reflect any changes)
```svelte
```
在服务器上,只能在渲染期间读取值(换句话说,不能在 `load` 函数中读取)。在浏览器中,可以随时读取值。
¥On the server, values can only be read during rendering (in other words *not* in e.g. `load` functions). In the browser, the values can be read at any time.
```dts
const page: import('@sveltejs/kit').Page;
```
## updated
最初为 `false` 的只读反应值。如果 [`version.pollInterval`](/docs/kit/configuration#version) 是非零值,SvelteKit 将轮询应用的新版本,并在检测到新版本时将 `current` 更新为 `true`。`updated.check()` 将强制立即检查,无论轮询如何。
¥A read-only reactive value that's initially `false`. If [`version.pollInterval`](/docs/kit/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update `current` to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling.
```dts
const updated: {
get current(): boolean;
check(): Promise;
};
```
# $app/stores
此模块包含 [`$app/state`]($app-state) 导出的基于存储的等效项。如果你使用的是 SvelteKit 2.12 或更高版本,请改用该模块。
¥This module contains store-based equivalents of the exports from [`$app/state`]($app-state). If you're using SvelteKit 2.12 or later, use that module instead.
```js
// @noErrors
import { getStores, navigating, page, updated } from '$app/stores';
```
## getStores
```dts
function getStores(): {
page: typeof page;
navigating: typeof navigating;
updated: typeof updated;
};
```
## navigating
改用 `$app/state` 中的 `navigating`(需要 Svelte 5、[查看文档了解更多信息](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))
¥Use `navigating` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))
可读存储。导航开始时,其值是具有 `from`、`to`、`type` 和(如果是 `type === 'popstate'`)`delta` 属性的 `Navigation` 对象。导航完成后,其值将恢复为 `null`。
¥A readable store.
When navigating starts, its value is a `Navigation` object with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties.
When navigating finishes, its value reverts to `null`.
在服务器上,只能在组件初始化期间订阅此存储。在浏览器中,可以随时订阅它。
¥On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.
```dts
const navigating: import('svelte/store').Readable<
import('@sveltejs/kit').Navigation | null
>;
```
## page
改用 `$app/state` 中的 `page`(需要 Svelte 5、[查看文档了解更多信息](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))
¥Use `page` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))
值包含页面数据的可读存储。
¥A readable store whose value contains page data.
在服务器上,只能在组件初始化期间订阅此存储。在浏览器中,可以随时订阅它。
¥On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.
```dts
const page: import('svelte/store').Readable<
import('@sveltejs/kit').Page
>;
```
## updated
改用 `$app/state` 中的 `updated`(需要 Svelte 5、[查看文档了解更多信息](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))
¥Use `updated` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))
初始值为 `false` 的可读存储。如果 [`version.pollInterval`](/docs/kit/configuration#version) 为非零值,SvelteKit 将轮询应用的新版本,并在检测到新版本时将存储值更新为 `true`。`updated.check()` 将强制立即检查,无论轮询如何。
¥A readable store whose initial value is `false`. If [`version.pollInterval`](/docs/kit/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update the store value to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling.
在服务器上,只能在组件初始化期间订阅此存储。在浏览器中,可以随时订阅它。
¥On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.
```dts
const updated: import('svelte/store').Readable & {
check(): Promise;
};
```
# $app/types
此模块包含你应用中路由的生成类型。
¥This module contains generated types for the routes in your app.
自 2.26 起可用
¥Available since 2.26
```js
// @noErrors
import type { RouteId, RouteParams, LayoutParams } from '$app/types';
```
## 资源(Asset)
¥Asset
`static` 目录中包含的所有资源文件名的并集,以及一个用于从 `import` 声明生成的资源路径的 `string` 通配符。
¥A union of all the filenames of assets contained in your `static` directory, plus a `string` wildcard for asset paths generated from `import` declarations.
```dts
type Asset = '/favicon.png' | '/robots.txt' | (string & {});
```
## RouteId
所有路由 ID 的联合应用。用于 `page.route.id` 和 `event.route.id`。
¥A union of all the route IDs in your app. Used for `page.route.id` and `event.route.id`.
```dts
type RouteId = '/' | '/my-route' | '/my-other-route/[param]';
```
## 路径名(Pathname)
¥Pathname
应用中所有有效路径名的联合。
¥A union of all valid pathnames in your app.
```dts
type Pathname = '/' | '/my-route' | `/my-other-route/${string}` & {};
```
## ResolvedPathname
与 `Pathname` 类似,但可能带有 [基本路径](configuration#paths) 前缀。用于 `page.url.pathname`。
¥Similar to `Pathname`, but possibly prefixed with a [base path](configuration#paths). Used for `page.url.pathname`.
```dts
type ResolvedPathname = `${'' | `/${string}`}/` | `${'' | `/${string}`}/my-route` | `${'' | `/${string}`}/my-other-route/${string}` | {};
```
## RouteParams
用于获取与给定路由关联的参数的实用程序。
¥A utility for getting the parameters associated with a given route.
```ts
// @errors: 2552
type BlogParams = RouteParams<'/blog/[slug]'>; // { slug: string }
```
```dts
type RouteParams = { /* generated */ } | Record;
```
## LayoutParams
用于获取与给定布局关联的参数的实用程序,类似于 `RouteParams`,但还包含任何子路由的可选参数。
¥A utility for getting the parameters associated with a given layout, which is similar to `RouteParams` but also includes optional parameters for any child route.
```dts
type RouteParams = { /* generated */ } | Record;
```
# $env/dynamic/private
此模块提供对运行时环境变量的访问,这些变量由你正在运行的平台定义。例如,如果你正在使用 [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node)(或运行 [`vite preview`](/docs/kit/cli)),这相当于 `process.env`。此模块仅包含不以 [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) 开头且以 [`config.kit.env.privatePrefix`](/docs/kit/configuration#env) 开头的变量(如果已配置)。
¥This module provides access to runtime environment variables, as defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](/docs/kit/cli)), this is equivalent to `process.env`. This module only includes variables that *do not* begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) *and do* start with [`config.kit.env.privatePrefix`](/docs/kit/configuration#env) (if configured).
此模块无法导入客户端代码。
¥This module cannot be imported into client-side code.
```ts
import { env } from '$env/dynamic/private';
console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE);
```
# $env/dynamic/public
与 [`$env/dynamic/private`](/docs/kit/$env-dynamic-private) 类似,但仅包含以 [`config.kit.env.publicPrefix`](/docs/kit/configuration#env)(默认为 `PUBLIC_`)开头的变量,因此可以安全地暴露给客户端代码。
¥Similar to [`$env/dynamic/private`](/docs/kit/$env-dynamic-private), but only includes variables that begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code.
请注意,公共动态环境变量必须全部从服务器发送到客户端,从而导致更大的网络请求 - 如果可能,请改用 `$env/static/public`。
¥Note that public dynamic environment variables must all be sent from the server to the client, causing larger network requests — when possible, use `$env/static/public` instead.
```ts
import { env } from '$env/dynamic/public';
console.log(env.PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE);
```
# $env/static/private
来自 `.env` 文件和 `process.env` 的环境变量 [由 Vite 加载](https://vitejs.dev/guide/env-and-mode.html#env-files)。与 [`$env/dynamic/private`](/docs/kit/$env-dynamic-private) 一样,此模块不能导入客户端代码。此模块仅包含不以 [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) 开头且以 [`config.kit.env.privatePrefix`](/docs/kit/configuration#env) 开头的变量(如果已配置)。
¥Environment variables [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env`. Like [`$env/dynamic/private`](/docs/kit/$env-dynamic-private), this module cannot be imported into client-side code. This module only includes variables that *do not* begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) *and do* start with [`config.kit.env.privatePrefix`](/docs/kit/configuration#env) (if configured).
与 [`$env/dynamic/private`](/docs/kit/$env-dynamic-private) 不同,从此模块导出的值在构建时静态注入到你的包中,从而实现诸如消除死代码之类的优化。
¥*Unlike* [`$env/dynamic/private`](/docs/kit/$env-dynamic-private), the values exported from this module are statically injected into your bundle at build time, enabling optimisations like dead code elimination.
```ts
import { API_KEY } from '$env/static/private';
```
请注意,代码中引用的所有环境变量都应声明(例如在 `.env` 文件中),即使它们在部署应用之前没有值:
¥Note that all environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed:
```
MY_FEATURE_FLAG=""
```
你可以像这样从命令行覆盖 `.env` 值:
¥You can override `.env` values from the command line like so:
```sh
MY_FEATURE_FLAG="enabled" npm run dev
```
# $env/static/public
与 [`$env/static/private`](/docs/kit/$env-static-private) 类似,不同之处在于它仅包含以 [`config.kit.env.publicPrefix`](/docs/kit/configuration#env)(默认为 `PUBLIC_`)开头的环境变量,因此可以安全地暴露给客户端代码。
¥Similar to [`$env/static/private`](/docs/kit/$env-static-private), except that it only includes environment variables that begin with [`config.kit.env.publicPrefix`](/docs/kit/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code.
值在构建时被静态替换。
¥Values are replaced statically at build time.
```ts
import { PUBLIC_BASE_URL } from '$env/static/public';
```
# $lib
SvelteKit 使用 `$lib` 导入别名自动提供 `src/lib` 下的文件。你可以在 [配置文件](configuration#files) 中更改此别名指向的目录。
¥SvelteKit automatically makes files under `src/lib` available using the `$lib` import alias. You can change which directory this alias points to in your [config file](configuration#files).
```svelte
A reusable component
```
```svelte
```
# $service-worker
```js
// @noErrors
import { base, build, files, prerendered, version } from '$service-worker';
```
此模块仅适用于 [服务工作者](/docs/kit/service-workers)。
¥This module is only available to [service workers](/docs/kit/service-workers).
## base
部署的 `base` 路径。通常,这相当于 `config.kit.paths.base`,但它是从 `location.pathname` 计算出来的,这意味着如果将站点部署到子目录,它将继续正常工作。请注意,有 `base` 但没有 `assets`,因为如果指定了 `config.kit.paths.assets`,则无法使用服务工作线程。
¥The `base` path of the deployment. Typically this is equivalent to `config.kit.paths.base`, but it is calculated from `location.pathname` meaning that it will continue to work correctly if the site is deployed to a subdirectory.
Note that there is a `base` but no `assets`, since service workers cannot be used if `config.kit.paths.assets` is specified.
```dts
const base: string;
```
## build
表示 Vite 生成的文件的 URL 字符串数组,适合使用 `cache.addAll(build)` 进行缓存。在开发过程中,这是一个空数组。
¥An array of URL strings representing the files generated by Vite, suitable for caching with `cache.addAll(build)`.
During development, this is an empty array.
```dts
const build: string[];
```
## files
表示静态目录中的文件或 `config.kit.files.assets` 指定的任何目录中的 URL 字符串数组。你可以使用 [`config.kit.serviceWorker.files`](/docs/kit/configuration#serviceWorker) 自定义从 `static` 目录包含哪些文件
¥An array of URL strings representing the files in your static directory, or whatever directory is specified by `config.kit.files.assets`. You can customize which files are included from `static` directory using [`config.kit.serviceWorker.files`](/docs/kit/configuration#serviceWorker)
```dts
const files: string[];
```
## prerendered
对应于预渲染页面和端点的路径名数组。在开发过程中,这是一个空数组。
¥An array of pathnames corresponding to prerendered pages and endpoints.
During development, this is an empty array.
```dts
const prerendered: string[];
```
## version
参见 [`config.kit.version`](/docs/kit/configuration#version)。它对于在服务工作线程中生成唯一的缓存名称很有用,以便以后部署应用可以使旧缓存无效。
¥See [`config.kit.version`](/docs/kit/configuration#version). It's useful for generating unique cache names inside your service worker, so that a later deployment of your app can invalidate old caches.
```dts
const version: string;
```
# 配置
你的项目配置位于项目根目录的 `svelte.config.js` 文件中。与 SvelteKit 一样,此配置对象还被其他与 Svelte 集成的工具(例如编辑器扩展)使用。
¥Your project's configuration lives in a `svelte.config.js` file at the root of your project. As well as SvelteKit, this config object is used by other tooling that integrates with Svelte such as editor extensions.
```js
/// file: svelte.config.js
// @filename: ambient.d.ts
declare module '@sveltejs/adapter-auto' {
const plugin: () => import('@sveltejs/kit').Adapter;
export default plugin;
}
// @filename: index.js
// ---cut---
import adapter from '@sveltejs/adapter-auto';
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
adapter: adapter()
}
};
export default config;
```
## 配置(Config)
¥Config
[`vite-plugin-svelte` 的选项](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#svelte-options) 的扩展。
¥An extension of [`vite-plugin-svelte`'s options](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md#svelte-options).
```dts
interface Config extends SvelteConfig {/*…*/}
```
```dts
kit?: KitConfig;
```
SvelteKit 选项。
¥SvelteKit options.
```dts
[key: string]: any;
```
组件中的任何 规则都将进行类似调整:
¥Any additional options required by tooling that integrates with Svelte.
## KitConfig
`kit` 属性配置 SvelteKit,并且可以具有以下属性:
¥The `kit` property configures SvelteKit, and can have the following properties:
## adapter
* 默认 `undefined`
¥default `undefined`
你的 [adapter](/docs/kit/adapters) 在执行 `vite build` 时运行。它决定如何为不同的平台转换输出。
¥Your [adapter](/docs/kit/adapters) is run when executing `vite build`. It determines how the output is converted for different platforms.
## alias
* 默认 `{}`
¥default `{}`
包含零个或多个别名的对象,用于替换 `import` 语句中的值。这些别名会自动传递给 Vite 和 TypeScript。
¥An object containing zero or more aliases used to replace values in `import` statements. These aliases are automatically passed to Vite and TypeScript.
```js
// @errors: 7031
/// file: svelte.config.js
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
alias: {
// this will match a file
'my-file': 'path/to/my-file.js',
// this will match a directory and its contents
// (`my-directory/x` resolves to `path/to/my-directory/x`)
'my-directory': 'path/to/my-directory',
// an alias ending /* will only match
// the contents of a directory, not the directory itself
'my-directory/*': 'path/to/my-directory/*'
}
}
};
```
## appDir
* 默认 `"_app"`
¥default `"_app"`
SvelteKit 保存其内容的目录,包括静态资源(例如 JS 和 CSS)和内部使用的路由。
¥The directory where SvelteKit keeps its stuff, including static assets (such as JS and CSS) and internally-used routes.
如果指定了 `paths.assets`,将有两个应用目录-`${paths.assets}/${appDir}` 和 `${paths.base}/${appDir}`。
¥If `paths.assets` is specified, there will be two app directories — `${paths.assets}/${appDir}` and `${paths.base}/${appDir}`.
## csp
[内容安全策略](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) 配置。CSP 通过限制可以从中加载资源的位置,帮助保护你的用户免受跨站点脚本 (XSS) 攻击。例如,像这样的配置...
¥[Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) configuration. CSP helps to protect your users against cross-site scripting (XSS) attacks, by limiting the places resources can be loaded from. For example, a configuration like this...
```js
// @errors: 7031
/// file: svelte.config.js
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
csp: {
directives: {
'script-src': ['self']
},
// must be specified with either the `report-uri` or `report-to` directives, or both
reportOnly: {
'script-src': ['self'],
'report-uri': ['/']
}
}
}
};
export default config;
```
...将阻止从外部站点加载脚本。SvelteKit 将使用 nonces 或哈希(取决于 `mode`)增强其生成的任何内联样式和脚本的指定指令。
¥...would prevent scripts loading from external sites. SvelteKit will augment the specified directives with nonces or hashes (depending on `mode`) for any inline styles and scripts it generates.
要为手动包含在 `src/app.html` 中的脚本和链接添加随机数,你可以使用占位符 `%sveltekit.nonce%`(例如 `
```
## paths
```ts
// @noErrors
assets?: '' | `http://${string}` | `https://${string}`;
```
* 默认 `""`
¥default `""`
你的应用文件的绝对路径。如果你的文件由某种存储桶提供,这将非常有用。
¥An absolute path that your app's files are served from. This is useful if your files are served from a storage bucket of some kind.
```ts
// @noErrors
base?: '' | `/${string}`;
```
* 默认 `""`
¥default `""`
必须以 `/`(例如 `/base-path`)开头但不能以 `/` 结尾的根相对路径,除非它是空字符串。这指定了你的应用的提供服务位置,并允许应用存在于非根路径上。请注意,你需要在所有根相关链接前面添加基值,否则它们将指向你的域的根目录,而不是你的 `base`(这是浏览器的工作方式)。你可以将 [`$app/paths` 中的 `base`](/docs/kit/$app-paths#base) 用于此目的:`
Link `。如果你发现自己经常写这个,那么将其提取到可重用的组件中可能很有意义。
¥A root-relative path that must start, but not end with `/` (e.g. `/base-path`), unless it is the empty string. This specifies where your app is served from and allows the app to live on a non-root path. Note that you need to prepend all your root-relative links with the base value or they will point to the root of your domain, not your `base` (this is how the browser works). You can use [`base` from `$app/paths`](/docs/kit/$app-paths#base) for that: `
Link `. If you find yourself writing this often, it may make sense to extract this into a reusable component.
```ts
// @noErrors
relative?: boolean;
```
* 默认 `true`
¥default `true`
* 自 v1.9.0 起可用
¥available since v1.9.0
是否使用相对资源路径。
¥Whether to use relative asset paths.
如果是 `true`,从 `$app/paths` 导入的 `base` 和 `assets` 将在服务器端渲染期间被替换为相对资源路径,从而产生更易于移植的 HTML。如果是 `false`,`%sveltekit.assets%` 和对构建工件的引用将始终是根相对路径,除非 `paths.assets` 是外部 URL
¥If `true`, `base` and `assets` imported from `$app/paths` will be replaced with relative asset paths during server-side rendering, resulting in more portable HTML.
If `false`, `%sveltekit.assets%` and references to build artifacts will always be root-relative paths, unless `paths.assets` is an external URL
[单页应用](/docs/kit/single-page-apps) 后备页面将始终使用绝对路径,无论此设置如何。
¥[Single-page app](/docs/kit/single-page-apps) fallback pages will always use absolute paths, regardless of this setting.
如果你的应用使用 `
` 元素,你应该将其设置为 `false`,否则资源 URL 将错误地根据 `
` URL 而不是当前页面进行解析。
¥If your app uses a `
` element, you should set this to `false`, otherwise asset URLs will incorrectly be resolved against the `
` URL rather than the current page.
在 1.0 中,`undefined` 是一个有效值,默认情况下设置。在这种情况下,如果 `paths.assets` 不是外部的,SvelteKit 会用相对路径替换 `%sveltekit.assets%`,并使用相对路径引用构建工件,但从 `$app/paths` 导入的 `base` 和 `assets` 将按照你的配置中指定的方式进行。
¥In 1.0, `undefined` was a valid value, which was set by default. In that case, if `paths.assets` was not external, SvelteKit would replace `%sveltekit.assets%` with a relative path and use relative paths to reference build artifacts, but `base` and `assets` imported from `$app/paths` would be as specified in your config.
## prerender
参见 [预渲染](/docs/kit/page-options#prerender)。
¥See [Prerendering](/docs/kit/page-options#prerender).
```ts
// @noErrors
concurrency?: number;
```
* 默认 `1`
¥default `1`
可以同时预渲染多少个页面。JS 是单线程的,但在预渲染性能受网络限制的情况下(例如从远程 CMS 加载内容),这可以通过在等待网络响应时处理其他任务来加快速度。
¥How many pages can be prerendered simultaneously. JS is single-threaded, but in cases where prerendering performance is network-bound (for example loading content from a remote CMS) this can speed things up by processing other tasks while waiting on the network response.
```ts
// @noErrors
crawl?: boolean;
```
* 默认 `true`
¥default `true`
SvelteKit 是否应通过跟踪 `entries` 中的链接来查找要预渲染的页面。
¥Whether SvelteKit should find pages to prerender by following links from `entries`.
```ts
// @noErrors
entries?: Array<'*' | `/${string}`>;
```
* 默认 `["*"]`
¥default `["*"]`
要预渲染或开始抓取的页面数组(如果是 `crawl: true`)。`*` 字符串包括所有不包含必需 `[parameters]` 的路由,其中包含的可选参数为空(因为 SvelteKit 不知道任何参数应该具有什么值)。
¥An array of pages to prerender, or start crawling from (if `crawl: true`). The `*` string includes all routes containing no required `[parameters]` with optional parameters included as being empty (since SvelteKit doesn't know what value any parameters should have).
```ts
// @noErrors
handleHttpError?: PrerenderHttpErrorHandlerValue;
```
* 默认 `"fail"`
¥default `"fail"`
* 自 v1.15.7 起可用
¥available since v1.15.7
如何响应预渲染应用时遇到的 HTTP 错误。
¥How to respond to HTTP errors encountered while prerendering the app.
* `'fail'` — 构建失败
¥`'fail'` — fail the build
* `'ignore'` - 默默忽略失败并继续
¥`'ignore'` - silently ignore the failure and continue
* `'warn'` — 继续,但打印警告
¥`'warn'` — continue, but print a warning
* `(details) => void` — 自定义错误处理程序,采用具有 `status`、`path`、`referrer`、`referenceType` 和 `message` 属性的 `details` 对象。如果你从此功能 `throw`,则构建将失败
¥`(details) => void` — a custom error handler that takes a `details` object with `status`, `path`, `referrer`, `referenceType` and `message` properties. If you `throw` from this function, the build will fail
```js
// @errors: 7031
/// file: svelte.config.js
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
prerender: {
handleHttpError: ({ path, referrer, message }) => {
// ignore deliberate link to shiny 404 page
if (path === '/not-found' && referrer === '/blog/how-we-built-our-404-page') {
return;
}
// otherwise fail the build
throw new Error(message);
}
}
}
};
```
```ts
// @noErrors
handleMissingId?: PrerenderMissingIdHandlerValue;
```
* 默认 `"fail"`
¥default `"fail"`
* 自 v1.15.7 起可用
¥available since v1.15.7
当从一个预渲染页面到另一个预渲染页面的哈希链接与目标页面上的 `id` 不对应时,如何响应。
¥How to respond when hash links from one prerendered page to another don't correspond to an `id` on the destination page.
* `'fail'` — 构建失败
¥`'fail'` — fail the build
* `'ignore'` - 默默忽略失败并继续
¥`'ignore'` - silently ignore the failure and continue
* `'warn'` — 继续,但打印警告
¥`'warn'` — continue, but print a warning
* `(details) => void` — 自定义错误处理程序,采用具有 `path`、`id`、`referrers` 和 `message` 属性的 `details` 对象。如果你从此功能 `throw`,则构建将失败
¥`(details) => void` — a custom error handler that takes a `details` object with `path`, `id`, `referrers` and `message` properties. If you `throw` from this function, the build will fail
```ts
// @noErrors
handleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue;
```
* 默认 `"fail"`
¥default `"fail"`
* 自 v1.16.0 起可用
¥available since v1.16.0
当 `entries` 导出生成的条目与其生成的路由不匹配时如何响应。
¥How to respond when an entry generated by the `entries` export doesn't match the route it was generated from.
* `'fail'` — 构建失败
¥`'fail'` — fail the build
* `'ignore'` - 默默忽略失败并继续
¥`'ignore'` - silently ignore the failure and continue
* `'warn'` — 继续,但打印警告
¥`'warn'` — continue, but print a warning
* `(details) => void` — 自定义错误处理程序,采用具有 `generatedFromId`、`entry`、`matchedId` 和 `message` 属性的 `details` 对象。如果你从此功能 `throw`,则构建将失败
¥`(details) => void` — a custom error handler that takes a `details` object with `generatedFromId`, `entry`, `matchedId` and `message` properties. If you `throw` from this function, the build will fail
```ts
// @noErrors
handleUnseenRoutes?: PrerenderUnseenRoutesHandlerValue;
```
* 默认 `"fail"`
¥default `"fail"`
* 自 v2.16.0 起可用
¥available since v2.16.0
当路由被标记为可预渲染但尚未预渲染时,如何响应。
¥How to respond when a route is marked as prerenderable but has not been prerendered.
* `'fail'` — 构建失败
¥`'fail'` — fail the build
* `'ignore'` - 默默忽略失败并继续
¥`'ignore'` - silently ignore the failure and continue
* `'warn'` — 继续,但打印警告
¥`'warn'` — continue, but print a warning
* `(details) => void` — 一个自定义错误处理程序,它接受一个带有 `routes` 属性的 `details` 对象,该属性包含所有尚未预渲染的路由。如果你从此功能 `throw`,则构建将失败
¥`(details) => void` — a custom error handler that takes a `details` object with a `routes` property which contains all routes that haven't been prerendered. If you `throw` from this function, the build will fail
默认行为是构建失败。当你知道某些路由在某些情况下可能永远无法访问时,这可能是不理想的,例如 CMS 不返回特定区域的数据,导致某些路由永远无法访问。
¥The default behavior is to fail the build. This may be undesirable when you know that some of your routes may never be reached under certain
circumstances such as a CMS not returning data for a specific area, resulting in certain routes never being reached.
```ts
// @noErrors
origin?: string;
```
* 默认 `"http://sveltekit-prerender"`
¥default `"http://sveltekit-prerender"`
预渲染期间 `url.origin` 的值;如果它包含在渲染的内容中,则很有用。
¥The value of `url.origin` during prerendering; useful if it is included in rendered content.
## router
```ts
// @noErrors
type?: 'pathname' | 'hash';
```
* 默认 `"pathname"`
¥default `"pathname"`
* 自 v2.14.0 起可用
¥available since v2.14.0
使用哪种类型的客户端路由。
¥What type of client-side router to use.
* `'pathname'` 是默认值,表示当前 URL 路径名决定路由
¥`'pathname'` is the default and means the current URL pathname determines the route
* `'hash'` 表示路由由 `location.hash` 确定。在这种情况下,SSR 和预渲染被禁用。仅当 `pathname` 不是一种选择时才建议这样做,例如因为你无法控制部署应用的 Web 服务器。它有一些注意事项:你不能使用服务器端渲染(或任何服务器逻辑),并且你必须确保应用中的链接都以 #/ 开头,否则它们将不起作用。除此之外,一切都与普通的 SvelteKit 应用完全一样。
¥`'hash'` means the route is determined by `location.hash`. In this case, SSR and prerendering are disabled. This is only recommended if `pathname` is not an option, for example because you don't control the webserver where your app is deployed.
It comes with some caveats: you can't use server-side rendering (or indeed any server logic), and you have to make sure that the links in your app all start with #/, or they won't work. Beyond that, everything works exactly like a normal SvelteKit app.
```ts
// @noErrors
resolution?: 'client' | 'server';
```
* 默认 `"client"`
¥default `"client"`
* 自 v2.17.0 起可用
¥available since v2.17.0
如何确定导航到新页面时要加载哪个路由。
¥How to determine which route to load when navigating to a new page.
默认情况下,SvelteKit 将向浏览器提供路由清单。导航时,此清单用于(如果存在,则与 `reroute` 钩子一起使用)确定要加载哪些组件以及要运行哪些 `load` 函数。因为一切都发生在客户端,所以这个决定可以立即做出。缺点是,在第一次导航之前需要加载和解析清单,如果你的应用包含许多路由,这可能会产生影响。
¥By default, SvelteKit will serve a route manifest to the browser.
When navigating, this manifest is used (along with the `reroute` hook, if it exists) to determine which components to load and which `load` functions to run.
Because everything happens on the client, this decision can be made immediately. The drawback is that the manifest needs to be
loaded and parsed before the first navigation can happen, which may have an impact if your app contains many routes.
或者,SvelteKit 可以确定服务器上的路由。这意味着对于每个尚未访问过的路径的导航,都会要求服务器确定路由。这有几个优点:
¥Alternatively, SvelteKit can determine the route on the server. This means that for every navigation to a path that has not yet been visited, the server will be asked to determine the route.
This has several advantages:
* 客户端不需要预先加载路由清单,这可以加快初始页面加载速度
¥The client does not need to load the routing manifest upfront, which can lead to faster initial page loads
* 路由列表对公众隐藏
¥The list of routes is hidden from public view
* 服务器有机会拦截每个导航(例如通过中间件),从而启用(例如)对 SvelteKit 不透明的 A/B 测试
¥The server has an opportunity to intercept each navigation (for example through a middleware), enabling (for example) A/B testing opaque to SvelteKit
缺点是对于未访问的路径,解析将花费更长的时间(尽管 [preloading](/docs/kit/link-options#data-sveltekit-preload-data) 可以缓解这种情况)。
¥The drawback is that for unvisited paths, resolution will take slightly longer (though this is mitigated by [preloading](/docs/kit/link-options#data-sveltekit-preload-data)).
## serviceWorker
## typescript
```ts
// @noErrors
config?: (config: Record
) => Record | void;
```
* 默认 `(config) => config`
¥default `(config) => config`
* 自 v1.3.0 起可用
¥available since v1.3.0
允许你编辑生成的 `tsconfig.json` 的函数。你可以改变配置(推荐)或返回新配置。例如,这对于在 monorepo 根中扩展共享 `tsconfig.json` 很有用。
¥A function that allows you to edit the generated `tsconfig.json`. You can mutate the config (recommended) or return a new one.
This is useful for extending a shared `tsconfig.json` in a monorepo root, for example.
请注意,此处配置的任何路径都应相对于生成的配置文件,该文件将写入 `.svelte-kit/tsconfig.json`。
¥Note that any paths configured here should be relative to the generated config file, which is written to `.svelte-kit/tsconfig.json`.
## version
如果在人们使用应用时部署新版本,客户端导航可能会出现错误。如果新页面的代码已加载,则可能包含过时的内容;如果不是,应用的路由清单可能会指向不再存在的 JavaScript 文件。SvelteKit 可帮助你通过版本管理解决此问题。如果 SvelteKit 在加载页面时遇到错误并检测到已部署新版本(使用此处指定的 `name`,默认为构建的时间戳),它将恢复到传统的全页导航。并非所有元素都有专用的类型定义。如果你仍然想在这些情况下强制进行全页导航,请使用设置 `pollInterval` 然后使用 `beforeNavigate` 等技术:
¥Client-side navigation can be buggy if you deploy a new version of your app while people are using it. If the code for the new page is already loaded, it may have stale content; if it isn't, the app's route manifest may point to a JavaScript file that no longer exists.
SvelteKit helps you solve this problem through version management.
If SvelteKit encounters an error while loading the page and detects that a new version has been deployed (using the `name` specified here, which defaults to a timestamp of the build) it will fall back to traditional full-page navigation.
Not all navigations will result in an error though, for example if the JavaScript for the next page is already loaded. If you still want to force a full-page navigation in these cases, use techniques such as setting the `pollInterval` and then using `beforeNavigate`:
```html
/// file: +layout.svelte
```
如果你将 `pollInterval` 设置为非零值,SvelteKit 将在后台轮询新版本,并在检测到新版本时设置 [`updated.current`](/docs/kit/$app-state#updated) `true` 的值。
¥If you set `pollInterval` to a non-zero value, SvelteKit will poll for new versions in the background and set the value of [`updated.current`](/docs/kit/$app-state#updated) `true` when it detects one.
```ts
// @noErrors
name?: string;
```
当前应用版本字符串。如果指定,这必须是确定性的(例如提交引用而不是 `Math.random()` 或 `Date.now().toString()`),否则默认为构建的时间戳。
¥The current app version string. If specified, this must be deterministic (e.g. a commit ref rather than `Math.random()` or `Date.now().toString()`), otherwise defaults to a timestamp of the build.
例如,要使用当前提交哈希,你可以使用 `git rev-parse HEAD`:
¥For example, to use the current commit hash, you could do use `git rev-parse HEAD`:
```js
// @errors: 7031
/// file: svelte.config.js
import * as child_process from 'node:child_process';
export default {
kit: {
version: {
name: child_process.execSync('git rev-parse HEAD').toString().trim()
}
}
};
```
```ts
// @noErrors
pollInterval?: number;
```
* 默认 `0`
¥default `0`
轮询版本更改的间隔(以毫秒为单位)。如果这是 `0`,则不会发生轮询。
¥The interval in milliseconds to poll for version changes. If this is `0`, no polling occurs.
# 命令行接口
SvelteKit 项目使用 [Vite](https://vitejs.dev),这意味着你将主要使用其 CLI(尽管通过 `npm run dev/build/preview` 脚本):
¥SvelteKit projects use [Vite](https://vitejs.dev), meaning you'll mostly use its CLI (albeit via `npm run dev/build/preview` scripts):
* `vite dev` — 启动开发服务器
¥`vite dev` — start a development server
* `vite build` — 构建应用的生产版本
¥`vite build` — build a production version of your app
* `vite preview` — 在本地运行生产版本
¥`vite preview` — run the production version locally
但是 SvelteKit 包含自己的 CLI 来初始化你的项目:
¥However SvelteKit includes its own CLI for initialising your project:
## svelte-kit sync
`svelte-kit sync` 为你的项目创建 `tsconfig.json` 和所有生成的类型(你可以在路由文件中将其作为 `./$types` 导入)。当你创建新项目时,它会被列为 `prepare` 脚本,并将作为 npm 生命周期的一部分自动运行,因此你通常不必运行此命令。
¥`svelte-kit sync` creates the `tsconfig.json` and all generated types (which you can import as `./$types` inside routing files) for your project. When you create a new project, it is listed as the `prepare` script and will be run automatically as part of the npm lifecycle, so you should not ordinarily have to run this command.
# 类型
## 生成的类型(Generated types)
¥Generated types
`RequestHandler` 和 `Load` 类型都接受 `Params` 参数,允许你输入 `params` 对象。例如,此端点需要 `foo`、`bar` 和 `baz` 参数:
¥The `RequestHandler` and `Load` types both accept a `Params` argument allowing you to type the `params` object. For example this endpoint expects `foo`, `bar` and `baz` params:
```js
/// file: src/routes/[foo]/[bar]/[baz]/+server.js
// @errors: 2355 2322 1360
/** @type {import('@sveltejs/kit').RequestHandler<{
foo: string;
bar: string;
baz: string
}>} */
export async function GET({ params }) {
// ...
}
```
不用说,这写起来很麻烦,而且移植性较差(如果你将 `[foo]` 目录重命名为 `[qux]`,则类型将不再反映现实)。
¥Needless to say, this is cumbersome to write out, and less portable (if you were to rename the `[foo]` directory to `[qux]`, the type would no longer reflect reality).
为了解决这个问题,SvelteKit 为你的每个端点和页面生成 `.d.ts` 文件:
¥To solve this problem, SvelteKit generates `.d.ts` files for each of your endpoints and pages:
```ts
/// file: .svelte-kit/types/src/routes/[foo]/[bar]/[baz]/$types.d.ts
/// link: true
import type * as Kit from '@sveltejs/kit';
type RouteParams = {
foo: string;
bar: string;
baz: string;
};
export type RequestHandler = Kit.RequestHandler;
export type PageLoad = Kit.Load;
```
由于 TypeScript 配置中的 [`rootDirs`](https://www.typescriptlang.org/tsconfig#rootDirs) 选项,这些文件可以作为同级文件导入到你的端点和页面中:
¥These files can be imported into your endpoints and pages as siblings, thanks to the [`rootDirs`](https://www.typescriptlang.org/tsconfig#rootDirs) option in your TypeScript configuration:
```js
/// file: src/routes/[foo]/[bar]/[baz]/+server.js
// @filename: $types.d.ts
import type * as Kit from '@sveltejs/kit';
type RouteParams = {
foo: string;
bar: string;
baz: string;
}
export type RequestHandler = Kit.RequestHandler;
// @filename: index.js
// @errors: 2355 2322
// ---cut---
/** @type {import('./$types').RequestHandler} */
export async function GET({ params }) {
// ...
}
```
```js
/// file: src/routes/[foo]/[bar]/[baz]/+page.js
// @filename: $types.d.ts
import type * as Kit from '@sveltejs/kit';
type RouteParams = {
foo: string;
bar: string;
baz: string;
}
export type PageLoad = Kit.Load;
// @filename: index.js
// @errors: 2355
// ---cut---
/** @type {import('./$types').PageLoad} */
export async function load({ params, fetch }) {
// ...
}
```
然后,加载函数的返回类型分别通过 `$types` 模块作为 `PageData` 和 `LayoutData` 提供,而所有 `Actions` 的返回值的并集作为 `ActionData` 提供。
¥The return types of the load functions are then available through the `$types` module as `PageData` and `LayoutData` respectively, while the union of the return values of all `Actions` is available as `ActionData`.
从 2.16.0 版开始,提供了两种额外的辅助程序类型:当定义了操作时,`PageProps` 定义 `data: PageData` 和 `form: ActionData`,而 `LayoutProps` 定义 `data: LayoutData` 和 `children: Snippet`。
¥Starting with version 2.16.0, two additional helper types are provided: `PageProps` defines `data: PageData`, as well as `form: ActionData`, when there are actions defined, while `LayoutProps` defines `data: LayoutData`, as well as `children: Snippet`.
```svelte
```
> 2.16.0 之前版本:
>
```svelte
>
>
> ```
>
> 使用 Svelte 4:
>
```svelte
>
>
> ```
>
> `{ "extends": "./.svelte-kit/tsconfig.json" }`
### 默认 tsconfig.json(Default tsconfig.json)
¥Default tsconfig.json
生成的 `.svelte-kit/tsconfig.json` 文件包含多种选项。有些是根据你的项目配置以编程方式生成的,通常不应在没有充分理由的情况下被覆盖:
¥The generated `.svelte-kit/tsconfig.json` file contains a mixture of options. Some are generated programmatically based on your project configuration, and should generally not be overridden without good reason:
```json
/// file: .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 正常工作所必需的,除非你知道自己在做什么,否则也应保持不变:
¥Others are required for SvelteKit to work properly, and should also be left untouched unless you know what you're doing:
```json
/// file: .svelte-kit/tsconfig.json
{
"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"
}
}
```
在 `svelte.config.js` 中使用 [`typescript.config` setting](configuration#typescript) 来扩展或修改生成的 `tsconfig.json`。
¥Use the [`typescript.config` setting](configuration#typescript) in `svelte.config.js` to extend or modify the generated `tsconfig.json`.
## $lib
这是 `src/lib` 的简单别名,或指定为 [`config.kit.files.lib`](configuration#files) 的任何目录。它允许你访问通用组件和实用程序模块,而无需 `../../../../` 废话。
¥This is a simple alias to `src/lib`, or whatever directory is specified as [`config.kit.files.lib`](configuration#files). It allows you to access common components and utility modules without `../../../../` nonsense.
### $lib/server
`$lib` 的子目录。SvelteKit 将阻止你将 `$lib/server` 中的任何模块导入客户端代码。参见 [服务器专用模块](server-only-modules)。
¥A subdirectory of `$lib`. SvelteKit will prevent you from importing any modules in `$lib/server` into client-side code. See [server-only modules](server-only-modules).
## app.d.ts
`app.d.ts` 文件是你应用的环境类型的所在地,即无需明确导入即可使用的类型。
¥The `app.d.ts` file is home to the ambient types of your apps, i.e. types that are available without explicitly importing them.
此文件始终是 `App` 命名空间的一部分。此命名空间包含几种类型,这些类型会影响你与之交互的某些 SvelteKit 功能的形状。
¥Always part of this file is the `App` namespace. This namespace contains several types that influence the shape of certain SvelteKit features you interact with.
## 错误(Error)
¥Error
定义预期和意外错误的共同形状。使用 `error` 函数会抛出预期错误。意外错误由 `handleError` 钩子处理,应返回此形状。
¥Defines the common shape of expected and unexpected errors. Expected errors are thrown using the `error` function. Unexpected errors are handled by the `handleError` hooks which should return this shape.
```dts
interface Error {/*…*/}
```
```dts
message: string;
```
## 本地(Locals)
¥Locals
定义 `event.locals` 的接口,可在服务器 [hooks](/docs/kit/hooks)(`handle` 和 `handleError`)、仅限服务器的 `load` 函数和 `+server.js` 文件中访问。
¥The interface that defines `event.locals`, which can be accessed in server [hooks](/docs/kit/hooks) (`handle`, and `handleError`), server-only `load` functions, and `+server.js` files.
```dts
interface Locals {}
```
## PageData
定义 [page.data 状态](/docs/kit/$app-state#page) 和 [$page.data store](/docs/kit/$app-stores#page) 的共同形状 - 即所有页面之间共享的数据。`./$types` 中的 `Load` 和 `ServerLoad` 函数将相应缩小。对仅存在于特定页面上的数据使用可选属性。不要添加索引签名(`[key: string]: any`)。
¥Defines the common shape of the [page.data state](/docs/kit/$app-state#page) and [$page.data store](/docs/kit/$app-stores#page) - that is, the data that is shared between all pages.
The `Load` and `ServerLoad` functions in `./$types` will be narrowed accordingly.
Use optional properties for data that is only present on specific pages. Do not add an index signature (`[key: string]: any`).
```dts
interface PageData {}
```
## PageState
`page.state` 对象的形状,可以使用 `$app/navigation` 中的 [`pushState`](/docs/kit/$app-navigation#pushState) 和 [`replaceState`](/docs/kit/$app-navigation#replaceState) 函数进行操作。
¥The shape of the `page.state` object, which can be manipulated using the [`pushState`](/docs/kit/$app-navigation#pushState) and [`replaceState`](/docs/kit/$app-navigation#replaceState) functions from `$app/navigation`.
```dts
interface PageState {}
```
## 平台(Platform)
¥Platform
如果你的适配器通过 `event.platform` 提供 [平台特定上下文](/docs/kit/adapters#Platform-specific-context),你可以在此处指定它。
¥If your adapter provides [platform-specific context](/docs/kit/adapters#Platform-specific-context) via `event.platform`, you can specify it here.
```dts
interface Platform {}
```
# Start of Svelte CLI documentation
# 概述
命令行接口 (CLI) `sv` 是用于创建和维护 Svelte 应用的工具包。
¥The command line interface (CLI), `sv`, is a toolkit for creating and maintaining Svelte applications.
## 用法(Usage)
¥Usage
运行 `sv` 的最简单方法是使用 [`npx`](https://www.npmjs.com/package/cli/v8/commands/npx)(或者如果你使用的是其他包管理器,则使用等效命令 - 例如,如果你使用的是 [pnpm](https://pnpm.io/),则使用 `pnpx`):
¥The easiest way to run `sv` is with [`npx`](https://www.npmjs.com/package/cli/v8/commands/npx) (or the equivalent command if you're using a different package manager — for example, `pnpx` if you're using [pnpm](https://pnpm.io/)):
```sh
npx sv
```
如果你在已经安装 `sv` 的项目中,这将使用本地安装,否则它将下载最新版本并运行它而不安装它,这对 [`sv create`](sv-create) 特别有用。
¥If you're inside a project where `sv` is already installed, this will use the local installation, otherwise it will download the latest version and run it without installing it, which is particularly useful for [`sv create`](sv-create).
## 致谢(Acknowledgements)
¥Acknowledgements
感谢 npm 上最初拥有 `sv` 名称的 [Christopher Brown](https://github.com/chbrown) 慷慨地允许它用于 Svelte CLI。你可以在 [`@chbrown/sv`](https://www.npmjs.com/package/@chbrown/sv) 找到原始 `sv` 包。
¥Thank you to [Christopher Brown](https://github.com/chbrown) who originally owned the `sv` name on npm for graciously allowing it to be used for the Svelte CLI. You can find the original `sv` package at [`@chbrown/sv`](https://www.npmjs.com/package/@chbrown/sv).
# 常见问题
## 如何运行 `sv` CLI?(How do I run the `sv` CLI?)
¥How do I run the `sv` CLI?
对于每个包管理器,运行 `sv` 看起来略有不同。以下是最常见的命令的列表:
¥Running `sv` looks slightly different for each package manager. Here is a list of the most common commands:
* npm : `npx sv create`
* pnpm:`pnpx sv create` 或 `pnpm dlx sv create`
¥**pnpm** : `pnpx sv create` or `pnpm dlx sv create`
* Bun : `bunx sv create`
* Deno : `deno run npm:sv create`
* Yarn : `yarn dlx sv create`
## `npx sv` 不起作用(`npx sv` is not working)
¥`npx sv` is not working
一些包管理器更喜欢运行本地安装的工具,而不是从注册表下载和执行包。此问题主要发生在 `npm` 和 `yarn` 上。这通常会导致错误消息,或者看起来你尝试执行的命令没有执行任何操作。
¥Some package managers prefer to run locally installed tools instead of downloading and executing packages from the registry. This issue mostly occurs with `npm` and `yarn`. This usually results in an error message or looks like the command you were trying to execute did not do anything.
以下是用户过去遇到的问题及其可能的解决方案的列表:
¥Here is a list of issues with possible solutions that users have encountered in the past:
* [`npx sv` create 不执行任何操作](https://github.com/sveltejs/cli/issues/472)
¥[`npx sv` create does nothing](https://github.com/sveltejs/cli/issues/472)
* [`sv` 命令名称与 `runit` 冲突](https://github.com/sveltejs/cli/issues/259)
¥[`sv` command name collides with `runit`](https://github.com/sveltejs/cli/issues/259)
* [Windows Powershell 中的 `sv` 与 `Set-Variable` 冲突](https://github.com/sveltejs/cli/issues/317)
¥[`sv` in windows powershell conflicts with `Set-Variable`](https://github.com/sveltejs/cli/issues/317)
# sv create
`sv create` 设置一个新的 SvelteKit 项目,并提供 [设置附加功能](sv-add#Official-add-ons) 选项。
¥`sv create` sets up a new SvelteKit project, with options to [setup additional functionality](sv-add#Official-add-ons).
## 用法(Usage)
¥Usage
```sh
npx sv create [options] [path]
```
## 选项(Options)
¥Options
### `--from-playground `
从 [playground](https://svelte.dev/playground) URL 创建 SvelteKit 项目。这将下载所有 Playground 文件,检测外部依赖,并设置完整的 SvelteKit 项目结构,一切准备就绪。
¥Create a SvelteKit project from a [playground](https://svelte.dev/playground) URL. This downloads all playground files, detects external dependencies, and sets up a complete SvelteKit project structure with everything ready to go.
示例:
¥Example:
```sh
npx sv create --from-playground="https://svelte.kfwddq.com/playground/hello-world"
```
### `--template `
使用哪个项目模板:
¥Which project template to use:
* `minimal` — 为你的新应用搭建基本框架
¥`minimal` — barebones scaffolding for your new app
* `demo` — 展示带有猜词游戏的应用,无需 JavaScript 即可运行
¥`demo` — showcase app with a word guessing game that works without JavaScript
* `library` — Svelte 库的模板,使用 `svelte-package` 设置
¥`library` — template for a Svelte library, set up with `svelte-package`
### `--types `
是否以及如何向项目添加类型检查:
¥Whether and how to add typechecking to the project:
* `ts` — 默认为 `.ts` 文件,对 `.svelte` 组件使用 `lang="ts"`
¥`ts` — default to `.ts` files and use `lang="ts"` for `.svelte` components
* `jsdoc` — 对类型使用 [JSDoc 语法](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html)
¥`jsdoc` — use [JSDoc syntax](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html) for types
### `--no-types`
防止添加类型检查。不推荐!
¥Prevent typechecking from being added. Not recommended!
### `--add [add-ons...]`
在 `create` 命令中向项目添加插件。遵循与 [sv add](sv-add#Usage) 相同的格式。
¥Add add-ons to the project in the `create` command. Following the same format as [sv add](sv-add#Usage).
示例:
¥Example:
```sh
npx sv create --add eslint prettier [path]
```
### `--no-add-ons`
在没有交互式附加组件提示的情况下运行命令
¥Run the command without the interactive add-ons prompt
### `--install `
使用指定的包管理器安装依赖:
¥Installs dependencies with a specified package manager:
* `npm`
* `pnpm`
* `yarn`
* `bun`
* `deno`
### `--no-install`
阻止安装依赖。
¥Prevents installing dependencies.
### `--no-dir-check`
跳过检查目标目录是否为空。
¥Skip checking whether the target directory is empty.
# sv add
`sv add` 将其统一为一个语法概念,该概念主要依赖于常规 JavaScript 解构语法。
¥`sv add` updates an existing project with new functionality.
## 用法(Usage)
¥Usage
```sh
npx sv add
```
```sh
npx sv add [add-ons]
```
你可以从 [下面的列表](#Official-add-ons) 中选择多个以空格分隔的附加组件,也可以使用交互式提示。
¥You can select multiple space-separated add-ons from [the list below](#Official-add-ons), or you can use the interactive prompt.
## 选项(Options)
¥Options
### `-C`, `--cwd`
Svelte(Kit) 项目的根目录路径。
¥Path to the root of your Svelte(Kit) project.
### `--no-git-check`
即使某些文件已修改,也不会显示任何提示
¥Even if some files are dirty, no prompt will be shown
### `--install `
使用指定的包管理器安装依赖:
¥Installs dependencies with a specified package manager:
* `npm`
* `pnpm`
* `yarn`
* `bun`
* `deno`
### `--no-install`
阻止安装依赖
¥Prevents installing dependencies
## 官方附加组件(Official add-ons)
¥Official add-ons
* [`devtools-json`](devtools-json)
* [`drizzle`](drizzle)
* [`eslint`](eslint)
* [`lucia`](lucia)
* [`mcp`](mcp)
* [`mdsvex`](mdsvex)
* [`paraglide`](paraglide)
* [`playwright`](playwright)
* [`prettier`](prettier)
* [`storybook`](storybook)
* [`sveltekit-adapter`](sveltekit-adapter)
* [`tailwindcss`](tailwind)
* [`vitest`](vitest)
# sv check
`sv check` 在你的项目中发现错误和警告,例如:
¥`sv check` finds errors and warnings in your project, such as:
* 未使用的 CSS
¥unused CSS
* 可访问性提示
¥accessibility hints
* JavaScript/TypeScript 编译器错误
¥JavaScript/TypeScript compiler errors
需要 Node 16 或更高版本。
¥Requires Node 16 or later.
## 安装(Installation)
¥Installation
你需要在项目中安装 `svelte-check` 软件包:
¥You will need to have the `svelte-check` package installed in your project:
```sh
npm i -D svelte-check
```
## 用法(Usage)
¥Usage
```sh
npx sv check
```
## 选项(Options)
¥Options
### `--workspace `
工作区路径。除 `node_modules` 和 `--ignore` 中列出的子目录外的所有子目录都经过检查。
¥Path to your workspace. All subdirectories except `node_modules` and those listed in `--ignore` are checked.
### `--output `
如何显示错误和警告。参见 [机器可读输出](#Machine-readable-output)。
¥How to display errors and warnings. See [machine-readable output](#Machine-readable-output).
* `human`
* `human-verbose`
* `machine`
* `machine-verbose`
### `--watch`
保持进程活跃并监视更改。
¥Keeps the process alive and watches for changes.
### `--preserveWatchOutput`
防止在监视模式下清除屏幕。
¥Prevents the screen from being cleared in watch mode.
### `--tsconfig `
传递 `tsconfig` 或 `jsconfig` 文件的路径。路径可以是相对于工作区路径的相对路径,也可以是绝对路径。这样做意味着只有与配置文件的 `files`/`include`/`exclude` 模式匹配的文件才会被诊断。它还意味着报告来自 TypeScript 和 JavaScript 文件的错误。如果没有给出,将从项目目录向上遍历寻找下一个 `jsconfig`/`tsconfig.json` 文件。
¥Pass a path to a `tsconfig` or `jsconfig` file. The path can be relative to the workspace path or absolute. Doing this means that only files matched by the `files`/`include`/`exclude` pattern of the config file are diagnosed. It also means that errors from TypeScript and JavaScript files are reported. If not given, will traverse upwards from the project directory looking for the next `jsconfig`/`tsconfig.json` file.
### `--no-tsconfig`
如果你只想检查当前目录及以下目录中的 Svelte 文件并忽略任何 `.js`/`.ts` 文件(它们不会被类型检查),请使用此功能
¥Use this if you only want to check the Svelte files found in the current directory and below and ignore any `.js`/`.ts` files (they will not be type-checked)
### `--ignore `
要忽略的文件/文件夹,相对于工作区根目录。路径应该用逗号分隔并加引号。示例:
¥Files/folders to ignore, relative to workspace root. Paths should be comma-separated and quoted. Example:
```sh
npx sv check --ignore "dist,build"
```
仅与 `--no-tsconfig` 结合使用时才有效。当与 `--tsconfig` 结合使用时,这只会对监视的文件产生影响,而不会对诊断的文件产生影响,然后由 `tsconfig.json` 确定。
¥Only has an effect when used in conjunction with `--no-tsconfig`. When used in conjunction with `--tsconfig`, this will only have effect on the files watched, not on the files that are diagnosed, which is then determined by the `tsconfig.json`.
### `--fail-on-warnings`
如果提供,警告将导致 `sv check` 退出并显示错误代码。
¥If provided, warnings will cause `sv check` to exit with an error code.
### `--compiler-warnings `
用引号括起来的逗号分隔的 `code:behaviour` 对列表,其中 `code` 是 [编译器警告代码](../svelte/compiler-warnings),而 `behaviour` 是 `ignore` 或 `error`:
¥A quoted, comma-separated list of `code:behaviour` pairs where `code` is a [compiler warning code](../svelte/compiler-warnings) and `behaviour` is either `ignore` or `error`:
```sh
npx sv check --compiler-warnings "css_unused_selector:ignore,a11y_missing_attribute:error"
```
### `--diagnostic-sources `
用引号括起来的逗号分隔的源列表,这些源应该在你的代码上运行诊断。默认情况下,所有都是活动的:
¥A quoted, comma-separated list of sources that should run diagnostics on your code. By default, all are active:
* `js`(包括 TypeScript)
¥`js` (includes TypeScript)
* `svelte`
* `css`
示例:
¥Example:
```sh
npx sv check --diagnostic-sources "js,svelte"
```
### `--threshold `
过滤诊断:
¥Filters the diagnostics:
* `warning`(默认) - 显示错误和警告
¥`warning` (default) — both errors and warnings are shown
* `error` — 仅显示错误
¥`error` — only errors are shown
## 故障排除(Troubleshooting)
¥Troubleshooting
[查看 language-tools 文档](https://github.com/sveltejs/language-tools/blob/master/docs/README.md) 有关预处理器设置和其他故障排除的更多信息。
¥[See the language-tools documentation](https://github.com/sveltejs/language-tools/blob/master/docs/README.md) for more information on preprocessor setup and other troubleshooting.
## 机器可读输出(Machine-readable output)
¥Machine-readable output
将 `--output` 设置为 `machine` 或 `machine-verbose` 将以更易于机器读取的方式格式化输出,例如在 CI 管道内部,用于代码质量检查等。
¥Setting the `--output` to `machine` or `machine-verbose` will format output in a way that is easier to read
by machines, e.g. inside CI pipelines, for code quality checks, etc.
每行对应一条新记录。行由由单个空格字符分隔的列组成。每行的第一列包含一个以毫秒为单位的时间戳,可用于监控目的。第二列为我们提供了 "运行脚本",后续列的数量和类型可能基于此而有所不同。
¥Each row corresponds to a new record. Rows are made up of columns that are separated by a
single space character. The first column of every row contains a timestamp in milliseconds
which can be used for monitoring purposes. The second column gives us the "row type", based
on which the number and types of subsequent columns may differ.
第一行是 `START` 类型,包含工作区文件夹(用引号括起来)。示例:
¥The first row is of type `START` and contains the workspace folder (wrapped in quotes). Example:
```
1590680325583 START "/home/user/language-tools/packages/language-server/test/plugins/typescript/testfiles"
```
可能随后有任意数量的 `ERROR` 或 `WARNING` 记录。它们的结构相同,取决于输出参数。
¥Any number of `ERROR` or `WARNING` records may follow. Their structure is identical and depends on the output argument.
如果参数是 `machine`,它将告诉我们文件名、起始行号和列号以及错误消息。文件名相对于工作区目录。文件名和消息都用引号括起来。示例:
¥If the argument is `machine` it will tell us the filename, the starting line and column numbers, and the error message. The filename is relative to the workspace directory. The filename and the message are both wrapped in quotes. Example:
```
1590680326283 ERROR "codeactions.svelte" 1:16 "Cannot find module 'blubb' or its corresponding type declarations."
1590680326778 WARNING "imported-file.svelte" 0:37 "Component has unused export property 'prop'. If it is for external reference only, please consider using `export const prop`"
```
如果参数是 `machine-verbose`,它将告诉我们文件名、起始行号和列号、结束行号和列号、错误消息、诊断代码、代码的人性化描述以及诊断的人性化来源(例如 svelte/typescript)。文件名相对于工作区目录。每个诊断都表示为以日志时间戳为前缀的 [ndjson](https://en.wikipedia.org/wiki/JSON_streaming#Newline-Delimited_JSON) 行。示例:
¥If the argument is `machine-verbose` it will tell us the filename, the starting line and column numbers, the ending line and column numbers, the error message, the code of diagnostic, the human-friendly description of the code and the human-friendly source of the diagnostic (eg. svelte/typescript). The filename is relative to the workspace directory. Each diagnostic is represented as an [ndjson](https://en.wikipedia.org/wiki/JSON_streaming#Newline-Delimited_JSON) line prefixed by the timestamp of the log. Example:
```
1590680326283 {"type":"ERROR","fn":"codeaction.svelte","start":{"line":1,"character":16},"end":{"line":1,"character":23},"message":"Cannot find module 'blubb' or its corresponding type declarations.","code":2307,"source":"js"}
1590680326778 {"type":"WARNING","filename":"imported-file.svelte","start":{"line":0,"character":37},"end":{"line":0,"character":51},"message":"Component has unused export property 'prop'. If it is for external reference only, please consider using `export
const prop`","code":"unused-export-let","source":"svelte"}
```
输出以 `COMPLETED` 消息结束,该消息总结了检查期间遇到的文件总数、错误和警告。示例:
¥The output concludes with a `COMPLETED` message that summarizes total numbers of files, errors and warnings that were encountered during the check. Example:
```
1590680326807 COMPLETED 20 FILES 21 ERRORS 1 WARNINGS 3 FILES_WITH_PROBLEMS
```
如果应用遇到运行时错误,此错误将显示为 `FAILURE` 记录。示例:
¥If the application experiences a runtime error, this error will appear as a `FAILURE` record. Example:
```
1590680328921 FAILURE "Connection closed"
```
## 致谢(Credits)
¥Credits
* 为 `svelte-check` 奠定基础的 Vue 的 [VTI](https://github.com/vuejs/vetur/tree/master/vti)
¥Vue's [VTI](https://github.com/vuejs/vetur/tree/master/vti) which laid the foundation for `svelte-check`
## 常见问题(FAQ)
¥FAQ
### 为什么没有仅检查特定文件的选项(例如仅暂存文件)?(Why is there no option to only check specific files (for example only staged files)?)
¥Why is there no option to only check specific files (for example only staged files)?
`svelte-check` 需要对整个项目进行 'see' 检查才能有效。假设你重命名了组件 prop,但没有更新使用该 prop 的任何地方 - 使用站点现在都是错误,但如果检查仅在更改的文件上运行,你会遗漏它们。
¥`svelte-check` needs to 'see' the whole project for checks to be valid. Suppose you renamed a component prop but didn't update any of the places where the prop is used — the usage sites are all errors now, but you would miss them if checks only ran on changed files.
# sv move
`sv migrate` 迁移 Svelte(Kit) 代码库。它委托给 [`svelte-migrate`](https://www.npmjs.com/package/svelte-migrate) 包。
¥`sv migrate` migrates Svelte(Kit) codebases. It delegates to the [`svelte-migrate`](https://www.npmjs.com/package/svelte-migrate) package.
某些迁移可能会用要完成的任务注释你的代码库,你可以通过搜索 `@migration` 找到这些任务。
¥Some migrations may annotate your codebase with tasks for completion that you can find by searching for `@migration`.
## 用法(Usage)
¥Usage
```sh
npx sv migrate
```
你也可以直接通过 CLI 指定迁移:
¥You can also specify a migration directly via the CLI:
```sh
npx sv migrate [migration]
```
## 迁移(Migrations)
¥Migrations
### `app-state`
将 `.svelte` 文件中的 `$app/stores` 使用迁移到 `$app/state`。有关更多详细信息,请参阅 [迁移指南](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated)。
¥Migrates `$app/stores` usage to `$app/state` in `.svelte` files. See the [migration guide](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated) for more details.
### `svelte-5`
升级 Svelte 4 应用以使用 Svelte 5,并更新各个组件以使用 [runes](../svelte/what-are-runes) 和其他 Svelte 5 语法 ([参见迁移指南](../svelte/v5-migration-guide))。
¥Upgrades a Svelte 4 app to use Svelte 5, and updates individual components to use [runes](../svelte/what-are-runes) and other Svelte 5 syntax ([see migration guide](../svelte/v5-migration-guide)).
### `self-closing-tags`
替换 `.svelte` 文件中的所有自闭合非空元素。有关更多详细信息,请参阅 [拉取请求](https://github.com/sveltejs/kit/pull/12128)。
¥Replaces all the self-closing non-void elements in your `.svelte` files. See the [pull request](https://github.com/sveltejs/kit/pull/12128) for more details.
### `svelte-4`
升级 Svelte 3 应用以使用 Svelte 4 ([参见迁移指南](../svelte/v4-migration-guide))。
¥Upgrades a Svelte 3 app to use Svelte 4 ([see migration guide](../svelte/v4-migration-guide)).
### `sveltekit-2`
将 SvelteKit 1 应用升级到 SvelteKit 2 ([参见迁移指南](../kit/migrating-to-sveltekit-2))。
¥Upgrades a SvelteKit 1 app to SvelteKit 2 ([see migration guide](../kit/migrating-to-sveltekit-2)).
### `package`
将使用 `@sveltejs/package` 版本 1 的库升级到版本 2。有关更多详细信息,请参阅 [拉取请求](https://github.com/sveltejs/kit/pull/8922)。
¥Upgrades a library using `@sveltejs/package` version 1 to version 2. See the [pull request](https://github.com/sveltejs/kit/pull/8922) for more details.
### `routes`
将预发布的 SvelteKit 应用升级为使用 SvelteKit 1 中的文件系统路由约定。有关更多详细信息,请参阅 [拉取请求](https://github.com/sveltejs/kit/discussions/5774)。
¥Upgrades a pre-release SvelteKit app to use the filesystem routing conventions in SvelteKit 1. See the [pull request](https://github.com/sveltejs/kit/discussions/5774) for more details.
# devtools-json
`devtools-json` 插件会安装 [`vite-plugin-devtools-json`](https://github.com/ChromeDevTools/vite-plugin-devtools-json/),这是一个 Vite 插件,用于在开发服务器中动态生成 Chromium DevTools 项目设置文件。此文件由 `/.well-known/appspecific/com.chrome.devtools.json` 提供,并告知 Chromium 浏览器项目源代码所在的位置,以便你可以使用 [工作区功能](https://developer.chrome.com/docs/devtools/workspaces) 在浏览器中编辑源文件。
¥The `devtools-json` add-on installs [`vite-plugin-devtools-json`](https://github.com/ChromeDevTools/vite-plugin-devtools-json/), which is a Vite plugin for generating a Chromium DevTools project settings file on-the-fly in the development server. This file is served from `/.well-known/appspecific/com.chrome.devtools.json` and tells Chromium browsers where your project's source code lives so that you can use [the workspaces feature](https://developer.chrome.com/docs/devtools/workspaces) to edit source files in the browser.
> 安装此插件后,所有使用 Chromium 浏览器连接到开发服务器的用户均可使用该功能,并允许浏览器读写目录中的所有文件。如果使用 Chrome 的 AI 辅助功能,则数据也可能会发送到 Google。
## 替代方案(Alternatives)
¥Alternatives
如果你不想安装该插件,但仍想避免看到有关文件丢失的消息,你有以下几种选择。
¥If you'd prefer not to install the plugin, but still want to avoid seeing a message about the missing file, you have a couple of options.
首先,你可以通过在浏览器中禁用该功能来阻止在你的计算机上发出请求。你可以在 Chrome 中访问 `chrome://flags` 并禁用 "DevTools 项目设置" 来执行此操作。你可能还想禁用 "DevTools 自动工作区文件夹",因为它与 密切相关。
¥Firstly, you can prevent the request from being issued on your machine by disabling the feature in your browser. You can do this in Chrome by visiting `chrome://flags` and disabling the "DevTools Project Settings". You may also be interested in disabling "DevTools Automatic Workspace Folders" since it’s closely related.
你还可以通过自行处理请求,阻止 Web 服务器向应用的所有开发者发出有关传入请求的通知。例如,你可以创建一个名为 `.well-known/appspecific/com.chrome.devtools.json` 的文件,其中包含 `"Go away, Chrome DevTools!"` 的内容,或者你可以在 [`handle`](https://svelte.kfwddq.com/docs/kit/hooks#Server-hooks-handle) 钩子中添加逻辑来响应请求:
¥You can also prevent the web server from issuing a notice regarding the incoming request for all developers of your application by handling the request yourself. For example, you can create a file named `.well-known/appspecific/com.chrome.devtools.json` with the contents `"Go away, Chrome DevTools!"` or you can add logic to respond to the request in your [`handle`](https://svelte.kfwddq.com/docs/kit/hooks#Server-hooks-handle) hook:
```js
/// file: src/hooks.server.js
import { dev } from '$app/environment';
export function handle({ event, resolve }) {
if (dev && event.url.pathname === '/.well-known/appspecific/com.chrome.devtools.json') {
return new Response(undefined, { status: 404 });
}
return resolve(event);
}
```
## 用法(Usage)
¥Usage
```sh
npx sv add devtools-json
```
## 你将获得什么(What you get)
¥What you get
* `vite-plugin-devtools-json` 已添加到你的 Vite 插件选项中
¥`vite-plugin-devtools-json` added to your Vite plugin options
# drizzle
[Drizzle ORM](https://orm.drizzle.team/) 是一个 TypeScript ORM,提供关系型和类 SQL 查询 API,并且在设计上支持无服务器架构。
¥[Drizzle ORM](https://orm.drizzle.team/) is a TypeScript ORM offering both relational and SQL-like query APIs, and which is serverless-ready by design.
## 用法(Usage)
¥Usage
```sh
npx sv add drizzle
```
## 你将获得什么(What you get)
¥What you get
* 一个将数据库访问保留在 SvelteKit 服务器文件中的设置
¥a setup that keeps your database access in SvelteKit's server files
* 一个 `.env` 文件,用于存储你的凭证
¥an `.env` file to store your credentials
* 与 Lucia 身份验证插件的兼容性
¥compatibility with the Lucia auth add-on
* 可选的 Docker 配置,用于帮助运行本地数据库
¥an optional Docker configuration to help with running a local database
## 选项(Options)
¥Options
### database
要使用哪种数据库变体:
¥Which database variant to use:
* `postgresql` — 最流行的开源数据库
¥`postgresql` — the most popular open source database
* `mysql` — 另一个流行的开源数据库
¥`mysql` — another popular open source database
* `sqlite` — 基于文件的数据库,不需要数据库服务器
¥`sqlite` — file-based database not requiring a database server
```sh
npx sv add drizzle="database:postgresql"
```
### client
要使用的 SQL 客户端取决于 `database`:
¥The SQL client to use, depends on `database`:
* 对于 `postgresql`:`postgres.js`, `neon`,
¥For `postgresql`: `postgres.js`, `neon`,
* 对于 `mysql`:`mysql2`, `planetscale`
¥For `mysql`: `mysql2`, `planetscale`
* 对于 `sqlite`:`better-sqlite3`, `libsql`, `turso`
¥For `sqlite`: `better-sqlite3`, `libsql`, `turso`
```sh
npx sv add drizzle="database:postgresql+client:postgres.js"
```
Drizzle 与十几种数据库驱动程序兼容。为了简单起见,我们仅提供一些最常用的适配器,但如果你想使用其他适配器,你可以选择一个作为占位符,并在设置后通过从 [Drizzle 的完整兼容驱动程序列表](https://orm.drizzle.team/docs/connect-overview#next-steps) 中选择将其替换为另一个。
¥Drizzle is compatible with well over a dozen database drivers. We just offer a few of the most common ones here for simplicity, but if you'd like to use another one you can choose one as a placeholder and swap it out for another after setup by choosing from [Drizzle's full list of compatible drivers](https://orm.drizzle.team/docs/connect-overview#next-steps).
### docker
是否添加 Docker Compose 配置。仅适用于 [`database`](#Options-database)、`postgresql` 或 `mysql`
¥Whether to add Docker Compose configuration. Only available for [`database`](#Options-database) `postgresql` or `mysql`
```sh
npx sv add drizzle="database:postgresql+client:postgres.js+docker:yes"
```
# eslint
[ESLint](https://eslint.org/) 可以查找并修复代码中的问题。
¥[ESLint](https://eslint.org/) finds and fixes problems in your code.
## 用法(Usage)
¥Usage
```sh
npx sv add eslint
```
## 你将获得什么(What you get)
¥What you get
* 已安装的相关软件包,包括 `eslint-plugin-svelte`
¥the relevant packages installed including `eslint-plugin-svelte`
* `eslint.config.js` 文件
¥an `eslint.config.js` file
* 更新后的 `.vscode/settings.json`
¥updated `.vscode/settings.json`
* 如果你使用 TypeScript 和 `prettier`,则配置为与这些软件包兼容
¥configured to work with TypeScript and `prettier` if you're using those packages
# lucia
遵循 [Lucia 身份验证指南](https://lucia-auth.com/) 的身份验证设置。
¥An auth setup following [the Lucia auth guide](https://lucia-auth.com/).
## 用法(Usage)
¥Usage
```sh
npx sv add lucia
```
## 你将获得什么(What you get)
¥What you get
* 遵循 Lucia 身份验证指南中的最佳实践,为 SvelteKit 和 Drizzle 设置身份验证
¥an auth setup for SvelteKit and Drizzle following the best practices from the Lucia auth guide
* 可选的演示注册和登录页面
¥optional demo registration and login pages
## 选项(Options)
¥Options
### demo
是否包含演示注册和登录页面。
¥Whether to include demo registration and login pages.
```sh
npx sv add lucia="demo:yes"
```
# mcp
[Svelte MCP](/docs/mcp/overview) 可以帮助你的 LLM 编写更好的 Svelte 代码。
¥[Svelte MCP](/docs/mcp/overview) can help your LLM write better Svelte code.
## 用法(Usage)
¥Usage
```sh
npx sv add mcp
```
## 你将获得什么(What you get)
¥What you get
* 用于 [local](https://svelte.kfwddq.com/docs/mcp/local-setup) 或 [remote](https://svelte.kfwddq.com/docs/mcp/remote-setup) 设置的 MCP 配置
¥An MCP configuration for [local](https://svelte.kfwddq.com/docs/mcp/local-setup) or [remote](https://svelte.kfwddq.com/docs/mcp/remote-setup) setup
* 一个 [代理的 README](https://agents.md/),可帮助你有效地使用 MCP 服务器。
¥A [README for agents](https://agents.md/) to help you use the MCP server effectively
## 选项(Options)
¥Options
### ide
你要使用的 IDE,例如 `'claude-code'`、`'cursor'`、`'gemini'`、`'opencode'`、`'vscode'`、`'other'`。
¥The IDE you want to use like `'claude-code'`, `'cursor'`, `'gemini'`, `'opencode'`, `'vscode'`, `'other'`.
```sh
npx sv add mcp="ide:cursor,vscode"
```
### setup
你要使用的设置。
¥The setup you want to use.
```sh
npx sv add mcp="setup:local"
```
# mdsvex
[mdsvex](https://mdsvex.pngwn.io) 是 Svelte 组件的 Markdown 预处理器 - 基本上是 Svelte 的 MDX。它允许你在 Markdown 中使用 Svelte 组件,或在 Svelte 组件中使用 Markdown。
¥[mdsvex](https://mdsvex.pngwn.io) is a markdown preprocessor for Svelte components - basically MDX for Svelte. It allows you to use Svelte components in your markdown, or markdown in your Svelte components.
## 用法(Usage)
¥Usage
```sh
npx sv add mdsvex
```
## 你将获得什么(What you get)
¥What you get
* 在你的 `svelte.config.js` 中安装并配置 mdsvex
¥mdsvex installed and configured in your `svelte.config.js`
# paraglide
[Inlang 的 Paraglide](https://inlang.com/m/gerre34r/library-inlang-paraglideJs) 是一个基于编译器的国际化库,它提供可摇树优化的消息函数,这些函数具有较小的包大小、无异步瀑布流、完全的类型安全等特点。
¥[Paraglide from Inlang](https://inlang.com/m/gerre34r/library-inlang-paraglideJs) is a compiler-based i18n library that emits tree-shakable message functions with small bundle sizes, no async waterfalls, full type-safety, and more.
## 用法(Usage)
¥Usage
```sh
npx sv add paraglide
```
## 你将获得什么(What you get)
¥What you get
* Inlang 项目设置
¥Inlang project settings
* paraglide Vite 插件
¥paraglide Vite plugin
* SvelteKit `reroute` 和 `handle` 钩子
¥SvelteKit `reroute` and `handle` hooks
* `app.html` 中的 `text-direction` 和 `lang` 属性
¥`text-direction` and `lang` attributes in `app.html`
* 更新后的 `.gitignore`
¥updated `.gitignore`
* 可选的演示页面,展示如何使用 paraglide
¥an optional demo page showing how to use paraglide
## 选项(Options)
¥Options
### languageTags
你希望支持的语言指定为 IETF BCP 47 语言标签。
¥The languages you'd like to support specified as IETF BCP 47 language tags.
```sh
npx sv add paraglide="languageTags:en,es"
```
### demo
是否生成一个可选的演示页面,展示如何使用 paraglide。
¥Whether to generate an optional demo page showing how to use paraglide.
```sh
npx sv add paraglide="demo:yes"
```
# playwright
[Playwright](https://playwright.dev) 浏览器测试。
¥[Playwright](https://playwright.dev) browser testing.
## 用法(Usage)
¥Usage
```sh
npx sv add playwright
```
## 你将获得什么(What you get)
¥What you get
* 在你的 `package.json` 中添加的脚本
¥scripts added in your `package.json`
* Playwright 配置文件
¥a Playwright config file
* 更新后的 `.gitignore`
¥an updated `.gitignore`
* 演示测试
¥a demo test
# prettier
[Prettier](https://prettier.io) 是一款自带代码格式化程序。
¥[Prettier](https://prettier.io) is an opinionated code formatter.
## 用法(Usage)
¥Usage
```sh
npx sv add prettier
```
## 你将获得什么(What you get)
¥What you get
* `package.json` 中的脚本
¥scripts in your `package.json`
* `.prettierignore` 和 `.prettierrc` 文件
¥`.prettierignore` and `.prettierrc` files
* 如果你正在使用该软件包,请更新你的 eslint 配置
¥updates to your eslint config if you're using that package
# storybook
[Storybook](https://storybook.js.org/) 是一个前端组件工作室。
¥[Storybook](https://storybook.js.org/) is a frontend component workshop.
## 用法(Usage)
¥Usage
```sh
npx sv add storybook
```
## 你将获得什么(What you get)
¥What you get
* `npx storybook init` 可以通过与其他所有插件相同的便捷 `sv` CLI 运行
¥`npx storybook init` run for you from the same convenient `sv` CLI used for all other add-ons
* [Storybook for SvelteKit](https://storybook.js.org/docs/get-started/frameworks/sveltekit) 或 [Storybook for Svelte 和 Vite](https://storybook.js.org/docs/get-started/frameworks/svelte-vite) 提供默认配置,可轻松模拟多种 SvelteKit 模块,并支持自动链接处理等功能。
¥[Storybook for SvelteKit](https://storybook.js.org/docs/get-started/frameworks/sveltekit) or [Storybook for Svelte & Vite](https://storybook.js.org/docs/get-started/frameworks/svelte-vite) with default config provided, easy mocking of many SvelteKit modules, automatic link handling, and more.
# sveltekit-adapter
[SvelteKit 适配器](/docs/kit/adapters) 允许你将网站部署到众多平台。此插件允许你配置官方提供的 SvelteKit 适配器,但也提供多种 [社区提供的适配器](https://www.sveltesociety.dev/packages?category=sveltekit-adapters) 适配器。
¥[SvelteKit adapters](/docs/kit/adapters) allow you to deploy your site to numerous platforms. This add-on allows you to configure officially provided SvelteKit adapters, but a number of [community-provided adapters](https://www.sveltesociety.dev/packages?category=sveltekit-adapters) are also available.
## 用法(Usage)
¥Usage
```sh
npx sv add sveltekit-adapter
```
## 你将获得什么(What you get)
¥What you get
* 在你的 `svelte.config.js` 中安装并配置所选的 SvelteKit 适配器
¥the chosen SvelteKit adapter installed and configured in your `svelte.config.js`
## 选项(Options)
¥Options
### adapter
要使用哪种 SvelteKit 适配器:
¥Which SvelteKit adapter to use:
* `auto` — [`@sveltejs/adapter-auto`](/docs/kit/adapter-auto) 自动选择要使用的适配器,但配置性较差
¥`auto` — [`@sveltejs/adapter-auto`](/docs/kit/adapter-auto) automatically chooses the proper adapter to use, but is less configurable
* `node` — [`@sveltejs/adapter-node`](/docs/kit/adapter-node) 生成独立的 Node 服务器
¥`node` — [`@sveltejs/adapter-node`](/docs/kit/adapter-node) generates a standalone Node server
* `static` — [`@sveltejs/adapter-static`](/docs/kit/adapter-static) 允许你使用 SvelteKit 作为静态站点生成器 (SSG)
¥`static` — [`@sveltejs/adapter-static`](/docs/kit/adapter-static) allows you to use SvelteKit as a static site generator (SSG)
* `vercel` — [`@sveltejs/adapter-vercel`](/docs/kit/adapter-vercel) 允许你部署到 Vercel
¥`vercel` — [`@sveltejs/adapter-vercel`](/docs/kit/adapter-vercel) allows you to deploy to Vercel
* `cloudflare` — [`@sveltejs/adapter-cloudflare`](/docs/kit/adapter-cloudflare) 允许你部署到 Cloudflare
¥`cloudflare` — [`@sveltejs/adapter-cloudflare`](/docs/kit/adapter-cloudflare) allows you to deploy to Cloudflare
* `netlify` — [`@sveltejs/adapter-netlify`](/docs/kit/adapter-netlify) 允许你部署到 Netlify
¥`netlify` — [`@sveltejs/adapter-netlify`](/docs/kit/adapter-netlify) allows you to deploy to Netlify
```sh
npx sv add sveltekit-adapter="adapter:node"
```
# tailwindcss
[Tailwind CSS](https://tailwindcss.com/) 允许你快速构建现代网站,而无需离开 HTML 页面。
¥[Tailwind CSS](https://tailwindcss.com/) allows you to rapidly build modern websites without ever leaving your HTML.
## 用法(Usage)
¥Usage
```sh
npx sv add tailwindcss
```
## 你将获得什么(What you get)
¥What you get
* 遵循 [Tailwind for SvelteKit 指南](https://tailwindcss.com/docs/installation/framework-guides/sveltekit) 的 Tailwind 设置
¥Tailwind setup following the [Tailwind for SvelteKit guide](https://tailwindcss.com/docs/installation/framework-guides/sveltekit)
* Tailwind Vite 插件
¥Tailwind Vite plugin
* 更新 `layout.css` 和 `+layout.svelte`(适用于 SvelteKit)或 `app.css` 和 `App.svelte`(适用于非 SvelteKit 的 Vite 应用)
¥updated `layout.css` and `+layout.svelte` (for SvelteKit) or `app.css` and `App.svelte` (for non-SvelteKit Vite apps)
* 如果使用 `prettier`,则与 `prettier` 集成
¥integration with `prettier` if using that package
## 选项(Options)
¥Options
### plugins
要使用的插件:
¥Which plugin to use:
* `typography` — [`@tailwindcss/typography`](https://github.com/tailwindlabs/tailwindcss-typography)
* `forms` — [`@tailwindcss/forms`](https://github.com/tailwindlabs/tailwindcss-forms)
```sh
npx sv add tailwindcss="plugins:typography"
```
# vitest
[Vitest](https://vitest.dev/) 是一个 Vite 原生测试框架。
¥[Vitest](https://vitest.dev/) is a Vite-native testing framework.
## 用法(Usage)
¥Usage
```sh
npx sv add vitest
```
## 你将获得什么(What you get)
¥What you get
* 已安装的相关软件包和已添加的脚本更新到你的 `package.json`
¥the relevant packages installed and scripts added to your `package.json`
* 在 Vite 配置文件中为 Svelte 设置客户端/服务器感知测试
¥client/server-aware testing setup for Svelte in your Vite config file
* 演示测试
¥demo tests
# Start of Svelte MCP documentation
# 概述
Svelte MCP ([模型上下文协议](https://modelcontextprotocol.io/docs/getting-started/intro)) 服务器可以帮助你的 LLM 或所选代理编写更好的 Svelte 代码。它的工作原理是提供与当前任务相关的文档,并静态分析生成的代码,以便提出修复建议和最佳实践。
¥The Svelte MCP ([Model Context Protocol](https://modelcontextprotocol.io/docs/getting-started/intro)) server can help your LLM or agent of choice write better Svelte code. It works by providing documentation relevant to the task at hand, and statically analysing generated code so that it can suggest fixes and best practices.
## 设置(Setup)
¥Setup
设置会根据你首选的 MCP 版本(远程或本地)以及你选择的 MCP 客户端(例如 Claude Code、Codex CLI 或 GitHub Copilot)而有所不同:
¥The setup varies based on the version of the MCP you prefer — remote or local — and your chosen MCP client (e.g. Claude Code, Codex CLI or GitHub Copilot):
* [本地设置](local-setup) 使用 `@sveltejs/mcp`
¥[local setup](local-setup) using `@sveltejs/mcp`
* [远程设置](remote-setup) 使用 `https://mcp.svelte.dev/mcp`
¥[remote setup](remote-setup) using `https://mcp.svelte.dev/mcp`
## 用法(Usage)
¥Usage
为了充分利用 MCP 服务器,我们建议在 [`AGENTS.md`](https://agents.md)(如果使用 Claude Code,则为 [`CLAUDE.md`](https://docs.claude.com/en/docs/claude-code/memory#claude-md-imports);如果使用 GEMINI,则为 [`GEMINI.md`](https://geminicli.com/docs/cli/gemini-md/))中包含以下提示。这将告诉 LLM 哪些工具可用以及何时适合使用它们。
¥To get the most out of the MCP server we recommend including the following prompt in your [`AGENTS.md`](https://agents.md) (or [`CLAUDE.md`](https://docs.claude.com/en/docs/claude-code/memory#claude-md-imports), if using Claude Code. Or [`GEMINI.md`](https://geminicli.com/docs/cli/gemini-md/), if using GEMINI). This will tell the LLM which tools are available and when it's appropriate to use them.
```md
You are able to use the Svelte MCP server, where you have access to comprehensive Svelte 5 and SvelteKit documentation. Here's how to use the available tools effectively:
## Available MCP Tools:
### 1. list-sections
Use this FIRST to discover all available documentation sections. Returns a structured list with titles, use_cases, and paths.
When asked about Svelte or SvelteKit topics, ALWAYS use this tool at the start of the chat to find relevant sections.
### 2. get-documentation
Retrieves full documentation content for specific sections. Accepts single or multiple sections.
After calling the list-sections tool, you MUST analyze the returned documentation sections (especially the use_cases field) and then use the get-documentation tool to fetch ALL documentation sections that are relevant for the user's task.
### 3. svelte-autofixer
Analyzes Svelte code and returns issues and suggestions.
You MUST use this tool whenever writing Svelte code before sending it to the user. Keep calling it until no issues or suggestions are returned.
### 4. playground-link
Generates a Svelte Playground link with the provided code.
After completing the code, ask the user if they want a playground link. Only call this tool after user confirmation and NEVER if code was written to files in their project.
```
如果你的 MCP 客户端支持,我们还建议你使用 [svelte-task](prompts#svelte-task) 提示符来指导 LLM 如何以最佳方式使用 MCP 服务器。
¥If your MCP client supports it, we also recommend using the [svelte-task](prompts#svelte-task) prompt to instruct the LLM on the best way to use the MCP server.
# 本地设置
MCP 服务器的本地(或 stdio)版本可通过 [`@sveltejs/mcp`](https://www.npmjs.com/package/@sveltejs/mcp) npm 包获取。你可以全局安装它,然后在配置中引用它,或者使用 `npx` 运行它:
¥The local (or stdio) version of the MCP server is available via the [`@sveltejs/mcp`](https://www.npmjs.com/package/@sveltejs/mcp) npm package. You can either install it globally and then reference it in your configuration or run it with `npx`:
```bash
npx -y @sveltejs/mcp
```
以下是如何在一些常见的 MCP 客户端中进行设置:
¥Here's how to set it up in some common MCP clients:
## Claude Code
要在 Claude Code 中包含本地 MCP 版本,只需运行以下命令:
¥To include the local MCP version in Claude Code, simply run the following command:
```bash
claude mcp add -t stdio -s [scope] svelte -- npx -y @sveltejs/mcp
```
`[scope]` 必须是 `user`、`project` 或 `local`。
¥The `[scope]` must be `user`, `project` or `local`.
## Claude Desktop
在“设置”>“开发者”部分中,点击“编辑配置”。它将打开包含 `claude_desktop_config.json` 文件的文件夹。编辑文件以包含以下配置:
¥In the Settings > Developer section, click on Edit Config. It will open the folder with a `claude_desktop_config.json` file in it. Edit the file to include the following configuration:
```json
{
"mcpServers": {
"svelte": {
"command": "npx",
"args": ["-y", "@sveltejs/mcp"]
}
}
}
```
## Codex CLI
将以下内容添加到你的 `config.toml`(默认为 `~/.codex/config.toml`,但有关更高级的设置,请参阅 [配置文档](https://github.com/openai/codex/blob/main/docs/config.md)):
¥Add the following to your `config.toml` (which defaults to `~/.codex/config.toml`, but refer to [the configuration documentation](https://github.com/openai/codex/blob/main/docs/config.md) for more advanced setups):
```toml
[mcp_servers.svelte]
command = "npx"
args = ["-y", "@sveltejs/mcp"]
```
## Gemini CLI
要在 Gemini CLI 中包含本地 MCP 版本,只需运行以下命令:
¥To include the local MCP version in Gemini CLI, simply run the following command:
```bash
gemini mcp add -t stdio -s [scope] svelte npx -y @sveltejs/mcp
```
`[scope]` 必须是 `user`、`project` 或 `local`。
¥The `[scope]` must be `user`, `project` or `local`.
## OpenCode
运行以下命令:
¥Run the command:
```bash
opencode mcp add
```
并按照说明操作,在 '选择 MCP 服务器类型' 提示符下选择 '本地':
¥and follow the instructions, selecting 'Local' under the 'Select MCP server type' prompt:
```bash
opencode mcp add
┌ Add MCP server
│
◇ Enter MCP server name
│ svelte
│
◇ Select MCP server type
│ Local
│
◆ Enter command to run
│ npx -y @sveltejs/mcp
```
## VS Code
* 打开命令面板
¥Open the command palette
* 选择“MCP:”添加服务器...
¥Select "MCP: Add Server..."
* 选择 "命令 (stdio)"
¥Select "Command (stdio)"
* 在输入框中插入 `npx -y @sveltejs/mcp` 并按下 `Enter`
¥Insert `npx -y @sveltejs/mcp` in the input and press `Enter`
* 当提示输入名称时,请插入 `svelte`
¥When prompted for a name, insert `svelte`
* 选择是否要将其添加为 `Global` 或 `Workspace` MCP 服务器
¥Select if you want to add it as a `Global` or `Workspace` MCP server
## Cursor
* 打开命令面板
¥Open the command palette
* 选择“查看:”打开“MCP 设置”
¥Select "View: Open MCP Settings"
* 点击 "添加自定义 MCP"
¥Click on "Add custom MCP"
它将打开一个包含你的 MCP 服务器的文件,你可以在其中添加以下配置:
¥It will open a file with your MCP servers where you can add the following configuration:
```json
{
"mcpServers": {
"svelte": {
"command": "npx",
"args": ["-y", "@sveltejs/mcp"]
}
}
}
```
## Zed
安装 [Svelte MCP 服务器扩展](https://zed.dev/extensions/svelte-mcp)。
¥Install the [Svelte MCP Server extension](https://zed.dev/extensions/svelte-mcp).
Configure Manually
* 打开命令面板
¥Open the command palette
* 搜索并选择 "agent:open 设置"
¥Search and select "agent:open settings"
* 在设置面板中查找 `Model Context Protocol (MCP) Servers`
¥In settings panel look for `Model Context Protocol (MCP) Servers`
* 点击 "添加服务器"
¥Click on "Add Server"
* 选择:"添加自定义服务器"
¥Select: "Add Custom Server"
它将打开一个包含 MCP 服务器配置的弹出窗口,你可以在其中添加以下配置:
¥It will open a popup with MCP server config where you can add the following configuration:
```json
{
"svelte": {
"command": "npx",
"args": ["-y", "@sveltejs/mcp"]
}
}
```
## 其他客户端(Other clients)
¥Other clients
如果我们未包含你正在使用的 MCP 客户端,请参阅其 `stdio` 服务器文档,并使用 `npx` 作为命令,`-y @sveltejs/mcp` 作为参数。
¥If we didn't include the MCP client you are using, refer to their documentation for `stdio` servers and use `npx` as the command and `-y @sveltejs/mcp` as the arguments.
# 远程设置
MCP 服务器的远程版本可在 `https://mcp.svelte.dev/mcp` 上获取。
¥The remote version of the MCP server is available at `https://mcp.svelte.dev/mcp`.
以下是如何在一些常见的 MCP 客户端中进行设置:
¥Here's how to set it up in some common MCP clients:
## Claude Code
要在 Claude Code 中包含远程 MCP 版本,只需运行以下命令:
¥To include the remote MCP version in Claude Code, simply run the following command:
```bash
claude mcp add -t http -s [scope] svelte https://mcp.svelte.dev/mcp
```
你可以选择你喜欢的 `scope`(必须是 `user`、`project` 或 `local`)和 `name`。
¥You can choose your preferred `scope` (it must be `user`, `project` or `local`) and `name`.
## Claude Desktop
* 打开“设置”>“连接器”
¥Open Settings > Connectors
* 点击“添加自定义连接器”
¥Click on Add Custom Connector
* 当提示输入名称时,请输入 `svelte`
¥When prompted for a name, enter `svelte`
* 在远程 MCP 服务器 URL 输入下,使用 `https://mcp.svelte.dev/mcp`
¥Under the Remote MCP server URL input, use `https://mcp.svelte.dev/mcp`
* 点击“添加”
¥Click Add
## Codex CLI
将以下内容添加到你的 `config.toml`(默认为 `~/.codex/config.toml`,但有关更高级的设置,请参阅 [配置文档](https://github.com/openai/codex/blob/main/docs/config.md)):
¥Add the following to your `config.toml` (which defaults to `~/.codex/config.toml`, but refer to [the configuration documentation](https://github.com/openai/codex/blob/main/docs/config.md) for more advanced setups):
```toml
experimental_use_rmcp_client = true
[mcp_servers.svelte]
url = "https://mcp.svelte.dev/mcp"
```
## Gemini CLI
要将远程 MCP 服务器与 Gemini CLI 一起使用,只需运行以下命令:
¥To use the remote MCP server with Gemini CLI, simply run the following command:
```bash
gemini mcp add -t http -s [scope] svelte https://mcp.svelte.dev/mcp
```
`[scope]` 必须是 `user` 或 `project`。
¥The `[scope]` must be `user` or `project`.
## OpenCode
运行以下命令:
¥Run the command:
```bash
opencode mcp add
```
并按照说明操作,在 '选择 MCP 服务器类型' 提示符下选择 '远程':
¥and follow the instructions, selecting 'Remote' under the 'Select MCP server type' prompt:
```bash
opencode mcp add
┌ Add MCP server
│
◇ Enter MCP server name
│ svelte
│
◇ Select MCP server type
│ Remote
│
◇ Enter MCP server URL
│ https://mcp.svelte.dev/mcp
```
## VS Code
* 打开命令面板
¥Open the command palette
* 选择“MCP:”添加服务器...
¥Select "MCP: Add Server..."
* 选择 "HTTP(HTTP 或服务器发送事件)"
¥Select "HTTP (HTTP or Server-Sent-Events)"
* 在输入框中插入 `https://mcp.svelte.dev/mcp` 并按下 `Enter`
¥Insert `https://mcp.svelte.dev/mcp` in the input and press `Enter`
* 输入你喜欢的名称
¥Insert your preferred name
* 选择是否要将其添加为 `Global` 或 `Workspace` MCP 服务器
¥Select if you want to add it as a `Global` or `Workspace` MCP server
## Cursor
* 打开命令面板
¥Open the command palette
* 选择“查看:”打开“MCP 设置”
¥Select "View: Open MCP Settings"
* 点击 "添加自定义 MCP"
¥Click on "Add custom MCP"
它将打开一个包含你的 MCP 服务器的文件,你可以在其中添加以下配置:
¥It will open a file with your MCP servers where you can add the following configuration:
```json
{
"mcpServers": {
"svelte": {
"url": "https://mcp.svelte.dev/mcp"
}
}
}
```
## GitHub Coding Agent
* 在 GitHub 中打开你的代码库
¥Open your repository in GitHub
* 前往“设置”
¥Go to Settings
* 打开 Copilot > Coding Agent
¥Open Copilot > Coding agent
* 编辑 MCP 配置
¥Edit the MCP configuration
```json
{
"mcpServers": {
"svelte": {
"type": "http",
"url": "https://mcp.svelte.dev/mcp",
"tools": ["*"]
}
}
}
```
* 点击“保存 MCP 配置”
¥Click *Save MCP configuration*
## 其他客户端(Other clients)
¥Other clients
如果我们未包含你正在使用的 MCP 客户端,请参阅其 `remote` 服务器文档,并使用 `https://mcp.svelte.dev/mcp` 作为 URL。
¥If we didn't include the MCP client you are using, refer to their documentation for `remote` servers and use `https://mcp.svelte.dev/mcp` as the URL.
# 工具
MCP 服务器为你所使用的模型提供了以下工具,模型可以决定在会话期间调用其中一个或多个工具:
¥The following tools are provided by the MCP server to the model you are using, which can decide to call one or more of them during a session:
## list-sections
提供所有可用文档部分的列表。
¥Provides a list of all the available documentation sections.
## get-documentation
允许模型直接从 [svelte.dev/docs](/docs) 获取所请求部分的完整(最新)文档。
¥Allows the model to get the full (and up-to-date) documentation for the requested sections directly from [svelte.dev/docs](/docs).
## svelte-autofixer
使用静态分析为你的 LLM 生成的代码提供建议。它可以由你的模型在代理循环中调用,直到所有问题和建议都得到解决。
¥Uses static analysis to provide suggestions for code that your LLM generates. It can be invoked in an agentic loop by your model until all issues and suggestions are resolved.
## playground-link
使用生成的代码生成一个临时的在线运行链接。当生成的代码未写入项目中的某个文件,并且你想要快速测试生成的解决方案时,它非常有用。除了 URL 本身(因此,URL 通常会非常大),代码不会存储在任何地方。
¥Generates an ephemeral playground link with the generated code. It's useful when the generated code is not written to a file in your project and you want to quickly test the generated solution. The code is not stored anywhere except the URL itself (which will often, as a consequence, be quite large).
# 资源
这是 MCP 服务器提供的可用资源列表。资源由用户(而非 LLM)加载,如果你想在会话中包含特定知识,则非常有用。例如,如果你知道组件需要使用转换,你可以直接包含转换文档,而无需请求 LLM 为你执行此操作。
¥This is the list of available resources provided by the MCP server. Resources are included by the user (not by the LLM) and are useful if you want to include specific knowledge in your session. For example, if you know that the component will need to use transitions you can include the transition documentation directly without asking the LLM to do it for you.
## doc-section
此动态资源允许你将 Svelte 文档的每个部分添加为资源。URI 类似于 `svelte://slug-of-the-docs.md`,返回的资源将包含你选择的特定页面的 `llms.txt` 版本。
¥This dynamic resource allows you to add every section of the Svelte documentation as a resource. The URI looks like this `svelte://slug-of-the-docs.md` and the returned resource will contain the `llms.txt` version of the specific page you selected.
# 提示
这是 MCP 服务器提供的可用提示列表。提示由用户选择,并作为用户消息发送。它们对于为 LLM 编写关于如何正确使用 MCP 服务器的重复说明非常有用。
¥This is the list of available prompts provided by the MCP server. Prompts are selected by the user and are sent as a user message. They can be useful to write repetitive instructions for the LLM on how to properly use the MCP server.
## svelte-task
每当你要求模型执行与 Svelte 相关的任务时,都应使用此提示。它将指示 LLM 哪些文档部分可用、调用哪些工具、何时调用它们以及如何解释结果。
¥This prompt should be used whenever you are asking the model to work on a Svelte-related task. It will instruct the LLM which documentation sections are available, which tools to invoke, when to invoke them, and how to interpret the results.
Copy the prompt
```md
You are a Svelte expert tasked to build components and utilities for Svelte developers. If you need documentation for anything related to Svelte you can invoke the tool `get_documentation` with one of the following paths:
- title: Overview, use_cases: project setup, creating new svelte apps, scaffolding, cli tools, initializing projects, path: cli/overview
- title: Frequently asked questions, use_cases: project setup, initializing new svelte projects, troubleshooting cli installation, package manager configuration, path: cli/faq
- title: sv create, use_cases: project setup, starting new sveltekit app, initializing project, creating from playground, choosing project template, path: cli/sv-create
- title: sv add, use_cases: project setup, adding features to existing projects, integrating tools, testing setup, styling setup, authentication, database setup, deployment adapters, path: cli/sv-add
- title: sv check, use_cases: code quality, ci/cd pipelines, error checking, typescript projects, pre-commit hooks, finding unused css, accessibility auditing, production builds, path: cli/sv-check
- title: sv migrate, use_cases: migration, upgrading svelte versions, upgrading sveltekit versions, modernizing codebase, svelte 3 to 4, svelte 4 to 5, sveltekit 1 to 2, adopting runes, refactoring deprecated apis, path: cli/sv-migrate
- title: devtools-json, use_cases: development setup, chrome devtools integration, browser-based editing, local development workflow, debugging setup, path: cli/devtools-json
- title: drizzle, use_cases: database setup, sql queries, orm integration, data modeling, postgresql, mysql, sqlite, server-side data access, database migrations, type-safe queries, path: cli/drizzle
- title: eslint, use_cases: code quality, linting, error detection, project setup, code standards, team collaboration, typescript projects, path: cli/eslint
- title: lucia, use_cases: authentication, login systems, user management, registration pages, session handling, auth setup, path: cli/lucia
- title: mcp, use_cases: use title and path to estimate use case, path: cli/mcp
- title: mdsvex, use_cases: blog, content sites, markdown rendering, documentation sites, technical writing, cms integration, article pages, path: cli/mdsvex
- title: paraglide, use_cases: internationalization, multi-language sites, i18n, translation, localization, language switching, global apps, multilingual content, path: cli/paraglide
- title: playwright, use_cases: browser testing, e2e testing, integration testing, test automation, quality assurance, ci/cd pipelines, testing user flows, path: cli/playwright
- title: prettier, use_cases: code formatting, project setup, code style consistency, team collaboration, linting configuration, path: cli/prettier
- title: storybook, use_cases: component development, design systems, ui library, isolated component testing, documentation, visual testing, component showcase, path: cli/storybook
- title: sveltekit-adapter, use_cases: deployment, production builds, hosting setup, choosing deployment platform, configuring adapters, static site generation, node server, vercel, cloudflare, netlify, path: cli/sveltekit-adapter
- title: tailwindcss, use_cases: project setup, styling, css framework, rapid prototyping, utility-first css, design systems, responsive design, adding tailwind to svelte, path: cli/tailwind
- title: vitest, use_cases: testing, unit tests, component testing, test setup, quality assurance, ci/cd pipelines, test-driven development, path: cli/vitest
- title: Introduction, use_cases: learning sveltekit, project setup, understanding framework basics, choosing between svelte and sveltekit, getting started with full-stack apps, path: kit/introduction
- title: Creating a project, use_cases: project setup, starting new sveltekit app, initial development environment, first-time sveltekit users, scaffolding projects, path: kit/creating-a-project
- title: Project types, use_cases: deployment, project setup, choosing adapters, ssg, spa, ssr, serverless, mobile apps, desktop apps, pwa, offline apps, browser extensions, separate backend, docker containers, path: kit/project-types
- title: Project structure, use_cases: project setup, understanding file structure, organizing code, starting new project, learning sveltekit basics, path: kit/project-structure
- title: Web standards, use_cases: always, any sveltekit project, data fetching, forms, api routes, server-side rendering, deployment to various platforms, path: kit/web-standards
- title: Routing, use_cases: routing, navigation, multi-page apps, project setup, file structure, api endpoints, data loading, layouts, error pages, always, path: kit/routing
- title: Loading data, use_cases: data fetching, api calls, database queries, dynamic routes, page initialization, loading states, authentication checks, ssr data, form data, content rendering, path: kit/load
- title: Form actions, use_cases: forms, user input, data submission, authentication, login systems, user registration, progressive enhancement, validation errors, path: kit/form-actions
- title: Page options, use_cases: prerendering static sites, ssr configuration, spa setup, client-side rendering control, url trailing slash handling, adapter deployment config, build optimization, path: kit/page-options
- title: State management, use_cases: sveltekit, server-side rendering, ssr, state management, authentication, data persistence, load functions, context api, navigation, component lifecycle, path: kit/state-management
- title: Remote functions, use_cases: data fetching, server-side logic, database queries, type-safe client-server communication, forms, user input, mutations, authentication, crud operations, optimistic updates, path: kit/remote-functions
- title: Building your app, use_cases: production builds, deployment preparation, build process optimization, adapter configuration, preview before deployment, path: kit/building-your-app
- title: Adapters, use_cases: deployment, production builds, hosting setup, choosing deployment platform, configuring adapters, path: kit/adapters
- title: Zero-config deployments, use_cases: deployment, production builds, hosting setup, choosing deployment platform, ci/cd configuration, path: kit/adapter-auto
- title: Node servers, use_cases: deployment, production builds, node.js hosting, custom server setup, environment configuration, reverse proxy setup, docker deployment, systemd services, path: kit/adapter-node
- title: Static site generation, use_cases: static site generation, ssg, prerendering, deployment, github pages, spa mode, blogs, documentation sites, marketing sites, path: kit/adapter-static
- title: Single-page apps, use_cases: spa mode, single-page apps, client-only rendering, static hosting, mobile app wrappers, no server-side logic, adapter-static setup, fallback pages, path: kit/single-page-apps
- title: Cloudflare, use_cases: deployment, cloudflare workers, cloudflare pages, hosting setup, production builds, serverless deployment, edge computing, path: kit/adapter-cloudflare
- title: Cloudflare Workers, use_cases: deploying to cloudflare workers, cloudflare workers sites deployment, legacy cloudflare adapter, wrangler configuration, cloudflare platform bindings, path: kit/adapter-cloudflare-workers
- title: Netlify, use_cases: deployment, netlify hosting, production builds, serverless functions, edge functions, static site hosting, path: kit/adapter-netlify
- title: Vercel, use_cases: deployment, vercel hosting, production builds, serverless functions, edge functions, isr, image optimization, environment variables, path: kit/adapter-vercel
- title: Writing adapters, use_cases: custom deployment, building adapters, unsupported platforms, adapter development, custom hosting environments, path: kit/writing-adapters
- title: Advanced routing, use_cases: advanced routing, dynamic routes, file viewers, nested paths, custom 404 pages, url validation, route parameters, multi-level navigation, path: kit/advanced-routing
- title: Hooks, use_cases: authentication, logging, error tracking, request interception, api proxying, custom routing, internationalization, database initialization, middleware logic, session management, path: kit/hooks
- title: Errors, use_cases: error handling, custom error pages, 404 pages, api error responses, production error logging, error tracking, type-safe errors, path: kit/errors
- title: Link options, use_cases: routing, navigation, multi-page apps, performance optimization, link preloading, forms with get method, search functionality, focus management, scroll behavior, path: kit/link-options
- title: Service workers, use_cases: offline support, pwa, caching strategies, performance optimization, precaching assets, network resilience, progressive web apps, path: kit/service-workers
- title: Server-only modules, use_cases: api keys, environment variables, sensitive data protection, backend security, preventing data leaks, server-side code isolation, path: kit/server-only-modules
- title: Snapshots, use_cases: forms, user input, preserving form data, multi-step forms, navigation state, preventing data loss, textarea content, input fields, comment systems, surveys, path: kit/snapshots
- title: Shallow routing, use_cases: modals, dialogs, image galleries, overlays, history-driven ui, mobile-friendly navigation, photo viewers, lightboxes, drawer menus, path: kit/shallow-routing
- title: Observability, use_cases: performance monitoring, debugging, observability, tracing requests, production diagnostics, analyzing slow requests, finding bottlenecks, monitoring server-side operations, path: kit/observability
- title: Packaging, use_cases: building component libraries, publishing npm packages, creating reusable svelte components, library development, package distribution, path: kit/packaging
- title: Auth, use_cases: authentication, login systems, user management, session handling, jwt tokens, protected routes, user credentials, authorization checks, path: kit/auth
- title: Performance, use_cases: performance optimization, slow loading pages, production deployment, debugging performance issues, reducing bundle size, improving load times, path: kit/performance
- title: Icons, use_cases: icons, ui components, styling, css frameworks, tailwind, unocss, performance optimization, dependency management, path: kit/icons
- title: Images, use_cases: image optimization, responsive images, performance, hero images, product photos, galleries, cms integration, cdn setup, asset management, path: kit/images
- title: Accessibility, use_cases: always, any sveltekit project, screen reader support, keyboard navigation, multi-page apps, client-side routing, internationalization, multilingual sites, path: kit/accessibility
- title: SEO, use_cases: seo optimization, search engine ranking, content sites, blogs, marketing sites, public-facing apps, sitemaps, amp pages, meta tags, performance optimization, path: kit/seo
- title: Frequently asked questions, use_cases: troubleshooting package imports, library compatibility issues, client-side code execution, external api integration, middleware setup, database configuration, view transitions, yarn configuration, path: kit/faq
- title: Integrations, use_cases: project setup, css preprocessors, postcss, scss, sass, less, stylus, typescript setup, adding integrations, tailwind, testing, auth, linting, formatting, path: kit/integrations
- title: Breakpoint Debugging, use_cases: debugging, breakpoints, development workflow, troubleshooting issues, vscode setup, ide configuration, inspecting code execution, path: kit/debugging
- title: Migrating to SvelteKit v2, use_cases: migration, upgrading from sveltekit 1 to 2, breaking changes, version updates, path: kit/migrating-to-sveltekit-2
- title: Migrating from Sapper, use_cases: migrating from sapper, upgrading legacy projects, sapper to sveltekit conversion, project modernization, path: kit/migrating
- title: Additional resources, use_cases: troubleshooting, getting help, finding examples, learning sveltekit, project templates, common issues, community support, path: kit/additional-resources
- title: Glossary, use_cases: rendering strategies, performance optimization, deployment configuration, seo requirements, static sites, spas, server-side rendering, prerendering, edge deployment, pwa development, path: kit/glossary
- title: @sveltejs/kit, use_cases: forms, form actions, server-side validation, form submission, error handling, redirects, json responses, http errors, server utilities, path: kit/@sveltejs-kit
- title: @sveltejs/kit/hooks, use_cases: middleware, request processing, authentication chains, logging, multiple hooks, request/response transformation, path: kit/@sveltejs-kit-hooks
- title: @sveltejs/kit/node/polyfills, use_cases: node.js environments, custom servers, non-standard runtimes, ssr setup, web api compatibility, polyfill requirements, path: kit/@sveltejs-kit-node-polyfills
- title: @sveltejs/kit/node, use_cases: node.js adapter, custom server setup, http integration, streaming files, node deployment, server-side rendering with node, path: kit/@sveltejs-kit-node
- title: @sveltejs/kit/vite, use_cases: project setup, vite configuration, initial sveltekit setup, build tooling, path: kit/@sveltejs-kit-vite
- title: $app/environment, use_cases: always, conditional logic, client-side code, server-side code, build-time logic, prerendering, development vs production, environment detection, path: kit/$app-environment
- title: $app/forms, use_cases: forms, user input, data submission, progressive enhancement, custom form handling, form validation, path: kit/$app-forms
- title: $app/navigation, use_cases: routing, navigation, multi-page apps, programmatic navigation, data reloading, preloading, shallow routing, navigation lifecycle, scroll handling, view transitions, path: kit/$app-navigation
- title: $app/paths, use_cases: static assets, images, fonts, public files, base path configuration, subdirectory deployment, cdn setup, asset urls, links, navigation, path: kit/$app-paths
- title: $app/server, use_cases: remote functions, server-side logic, data fetching, form handling, api endpoints, client-server communication, prerendering, file reading, batch queries, path: kit/$app-server
- title: $app/state, use_cases: routing, navigation, multi-page apps, loading states, url parameters, form handling, error states, version updates, page metadata, shallow routing, path: kit/$app-state
- title: $app/stores, use_cases: legacy projects, sveltekit pre-2.12, migration from stores to runes, maintaining older codebases, accessing page data, navigation state, app version updates, path: kit/$app-stores
- title: $app/types, use_cases: routing, navigation, type safety, route parameters, dynamic routes, link generation, pathname validation, multi-page apps, path: kit/$app-types
- title: $env/dynamic/private, use_cases: api keys, secrets management, server-side config, environment variables, backend logic, deployment-specific settings, private data handling, path: kit/$env-dynamic-private
- title: $env/dynamic/public, use_cases: environment variables, client-side config, runtime configuration, public api keys, deployment-specific settings, multi-environment apps, path: kit/$env-dynamic-public
- title: $env/static/private, use_cases: server-side api keys, backend secrets, database credentials, private configuration, build-time optimization, server endpoints, authentication tokens, path: kit/$env-static-private
- title: $env/static/public, use_cases: environment variables, public config, client-side data, api endpoints, build-time configuration, public constants, path: kit/$env-static-public
- title: $lib, use_cases: project setup, component organization, importing shared components, reusable ui elements, code structure, path: kit/$lib
- title: $service-worker, use_cases: offline support, pwa, service workers, caching strategies, progressive web apps, offline-first apps, path: kit/$service-worker
- title: Configuration, use_cases: project setup, configuration, adapters, deployment, build settings, environment variables, routing customization, prerendering, csp security, csrf protection, path configuration, typescript setup, path: kit/configuration
- title: Command Line Interface, use_cases: project setup, typescript configuration, generated types, ./$types imports, initial project configuration, path: kit/cli
- title: Types, use_cases: typescript, type safety, route parameters, api endpoints, load functions, form actions, generated types, jsconfig setup, path: kit/types
- title: Overview, use_cases: use title and path to estimate use case, path: mcp/overview
- title: Local setup, use_cases: use title and path to estimate use case, path: mcp/local-setup
- title: Remote setup, use_cases: use title and path to estimate use case, path: mcp/remote-setup
- title: Tools, use_cases: use title and path to estimate use case, path: mcp/tools
- title: Resources, use_cases: use title and path to estimate use case, path: mcp/resources
- title: Prompts, use_cases: use title and path to estimate use case, path: mcp/prompts
- title: Overview, use_cases: always, any svelte project, getting started, learning svelte, introduction, project setup, understanding framework basics, path: svelte/overview
- title: Getting started, use_cases: project setup, starting new svelte project, initial installation, choosing between sveltekit and vite, editor configuration, path: svelte/getting-started
- title: .svelte files, use_cases: always, any svelte project, component creation, project setup, learning svelte basics, path: svelte/svelte-files
- title: .svelte.js and .svelte.ts files, use_cases: shared reactive state, reusable reactive logic, state management across components, global stores, custom reactive utilities, path: svelte/svelte-js-files
- title: What are runes?, use_cases: always, any svelte 5 project, understanding core syntax, learning svelte 5, migration from svelte 4, path: svelte/what-are-runes
- title: $state, use_cases: always, any svelte project, core reactivity, state management, counters, forms, todo apps, interactive ui, data updates, class-based components, path: svelte/$state
- title: $derived, use_cases: always, any svelte project, computed values, reactive calculations, derived data, transforming state, dependent values, path: svelte/$derived
- title: $effect, use_cases: canvas drawing, third-party library integration, dom manipulation, side effects, intervals, timers, network requests, analytics tracking, path: svelte/$effect
- title: $props, use_cases: always, any svelte project, passing data to components, component communication, reusable components, component props, path: svelte/$props
- title: $bindable, use_cases: forms, user input, two-way data binding, custom input components, parent-child communication, reusable form fields, path: svelte/$bindable
- title: $inspect, use_cases: debugging, development, tracking state changes, reactive state monitoring, troubleshooting reactivity issues, path: svelte/$inspect
- title: $host, use_cases: custom elements, web components, dispatching custom events, component library, framework-agnostic components, path: svelte/$host
- title: Basic markup, use_cases: always, any svelte project, basic markup, html templating, component structure, attributes, events, props, text rendering, path: svelte/basic-markup
- title: {#if ...}, use_cases: always, conditional rendering, showing/hiding content, dynamic ui, user permissions, loading states, error handling, form validation, path: svelte/if
- title: {#each ...}, use_cases: always, lists, arrays, iteration, product listings, todos, tables, grids, dynamic content, shopping carts, user lists, comments, feeds, path: svelte/each
- title: {#key ...}, use_cases: animations, transitions, component reinitialization, forcing component remount, value-based ui updates, resetting component state, path: svelte/key
- title: {#await ...}, use_cases: async data fetching, api calls, loading states, promises, error handling, lazy loading components, dynamic imports, path: svelte/await
- title: {#snippet ...}, use_cases: reusable markup, component composition, passing content to components, table rows, list items, conditional rendering, reducing duplication, path: svelte/snippet
- title: {@render ...}, use_cases: reusable ui patterns, component composition, conditional rendering, fallback content, layout components, slot alternatives, template reuse, path: svelte/@render
- title: {@html ...}, use_cases: rendering html strings, cms content, rich text editors, markdown to html, blog posts, wysiwyg output, sanitized html injection, dynamic html content, path: svelte/@html
- title: {@attach ...}, use_cases: tooltips, popovers, dom manipulation, third-party libraries, canvas drawing, element lifecycle, interactive ui, custom directives, wrapper components, path: svelte/@attach
- title: {@const ...}, use_cases: computed values in loops, derived calculations in blocks, local variables in each iterations, complex list rendering, path: svelte/@const
- title: {@debug ...}, use_cases: debugging, development, troubleshooting, tracking state changes, monitoring variables, reactive data inspection, path: svelte/@debug
- title: bind:, use_cases: forms, user input, two-way data binding, interactive ui, media players, file uploads, checkboxes, radio buttons, select dropdowns, contenteditable, dimension tracking, path: svelte/bind
- title: use:, use_cases: custom directives, dom manipulation, third-party library integration, tooltips, click outside, gestures, focus management, element lifecycle hooks, path: svelte/use
- title: transition:, use_cases: animations, interactive ui, modals, dropdowns, notifications, conditional content, show/hide elements, smooth state changes, path: svelte/transition
- title: in: and out:, use_cases: animation, transitions, interactive ui, conditional rendering, independent enter/exit effects, modals, tooltips, notifications, path: svelte/in-and-out
- title: animate:, use_cases: sortable lists, drag and drop, reorderable items, todo lists, kanban boards, playlist editors, priority queues, animated list reordering, path: svelte/animate
- title: style:, use_cases: dynamic styling, conditional styles, theming, dark mode, responsive design, interactive ui, component styling, path: svelte/style
- title: class, use_cases: always, conditional styling, dynamic classes, tailwind css, component styling, reusable components, responsive design, path: svelte/class
- title: await, use_cases: async data fetching, loading states, server-side rendering, awaiting promises in components, async validation, concurrent data loading, path: svelte/await-expressions
- title: Scoped styles, use_cases: always, styling components, scoped css, component-specific styles, preventing style conflicts, animations, keyframes, path: svelte/scoped-styles
- title: Global styles, use_cases: global styles, third-party libraries, css resets, animations, styling body/html, overriding component styles, shared keyframes, base styles, path: svelte/global-styles
- title: Custom properties, use_cases: theming, custom styling, reusable components, design systems, dynamic colors, component libraries, ui customization, path: svelte/custom-properties
- title: Nested