` 不再是必需的。
¥Remove `%sapper.base%`, `%sapper.scripts%` and `%sapper.styles%`. Replace `%sapper.head%` with `%sveltekit.head%` and `%sapper.html%` with `%sveltekit.body%`. The `
` is no longer necessary.
### src/node\_modules
Sapper 应用中的常见模式是将内部库放在 `src/node_modules` 内的目录中。这不适用于 Vite,因此我们改用 [`src/lib`]($lib)。
¥A common pattern in Sapper apps is to put your internal library in a directory inside `src/node_modules`. This doesn't work with Vite, so we use [`src/lib`]($lib) instead.
## 页面和布局(Pages and layouts)
¥Pages and layouts
### 重命名文件(Renamed files)
¥Renamed files
为了消除歧义,现在的路由仅由文件夹名称组成,文件夹名称指向 `+page.svelte` 对应于路由。有关概述,请参阅 [路由文档](routing)。以下显示了旧/新比较:
¥Routes now are made up of the folder name exclusively to remove ambiguity, the folder names leading up to a `+page.svelte` correspond to the route. See [the routing docs](routing) for an overview. The following shows a old/new comparison:
| 旧 | 新 |
| ------------------------- | --- |
| routes/about/index.svelte | 行类型 |
| routes/about.svelte | 行类型 |
你的自定义错误页面组件应从 `_error.svelte` 重命名为 `+error.svelte`。任何 `_layout.svelte` 都作为 DOM 元素的属性公开(以及在可能的情况下作为属性可读/可写)。[忽略任何其他文件](routing#Other-files)。
¥Your custom error page component should be renamed from `_error.svelte` to `+error.svelte`. Any `_layout.svelte` files should likewise be renamed `+layout.svelte`. [Any other files are ignored](routing#Other-files).
### 导入(Imports)
¥Imports
来自 `@sapper/app` 的 `goto`、`prefetch` 和 `prefetchRoutes` 导入应分别替换为来自 [`$app/navigation`]($app-navigation) 的 `goto`、`preloadData` 和 `preloadCode` 导入。
¥The `goto`, `prefetch` and `prefetchRoutes` imports from `@sapper/app` should be replaced with `goto`, `preloadData` and `preloadCode` imports respectively from [`$app/navigation`]($app-navigation).
应替换从 `@sapper/app` 导入的 `stores` — 请参阅下面的 [存储](migrating#Pages-and-layouts-Stores) 部分。
¥The `stores` import from `@sapper/app` should be replaced — see the [Stores](migrating#Pages-and-layouts-Stores) section below.
你之前从 `src/node_modules` 目录中导入的任何文件都需要用 [`$lib`]($lib) 导入替换。
¥Any files you previously imported from directories in `src/node_modules` will need to be replaced with [`$lib`]($lib) imports.
### 预加载(Preload)
¥Preload
与以前一样,页面和布局可以导出一个函数,允许在渲染之前加载数据。
¥As before, pages and layouts can export a function that allows data to be loaded before rendering takes place.
此函数已从 `preload` 重命名为 [`load`](load),它现在位于其 `+page.svelte`(或 `+layout.svelte`)旁边的 `+page.js`(或 `+layout.js`)中,并且其 API 已更改。不再有两个参数 — `page` 和 `session` — 而是一个 `event` 参数。
¥This function has been renamed from `preload` to [`load`](load), it now lives in a `+page.js` (or `+layout.js`) next to its `+page.svelte` (or `+layout.svelte`), and its API has changed. Instead of two arguments — `page` and `session` — there is a single `event` argument.
不再有 `this` 对象,因此也没有 `this.fetch`、`this.error` 或 `this.redirect`。相反,你可以从输入法中获取 [`fetch`](load#Making-fetch-requests),现在会抛出 [`error`](load#Errors) 和 [`redirect`](load#Redirects)。
¥There is no more `this` object, and consequently no `this.fetch`, `this.error` or `this.redirect`. Instead, you can get [`fetch`](load#Making-fetch-requests) from the input methods, and both [`error`](load#Errors) and [`redirect`](load#Redirects) are now thrown.
### 存储(Stores)
¥Stores
在 Sapper 中,你将获得对提供的存储的引用,如下所示:
¥In Sapper, you would get references to provided stores like so:
```js
// @filename: ambient.d.ts
declare module '@sapper/app';
// @filename: index.js
// ---cut---
import { stores } from '@sapper/app';
const { preloading, page, session } = stores();
```
`page` 存储仍然存在;`preloading` 已被替换为包含 `from` 和 `to` 属性的 `navigating` 存储。`page` 现在具有 `url` 和 `params` 属性,但没有 `path` 或 `query`。
¥The `page` store still exists; `preloading` has been replaced with a `navigating` store that contains `from` and `to` properties. `page` now has `url` and `params` properties, but no `path` or `query`.
你可以在 SvelteKit 中以不同的方式访问它们。`stores` 现在是 `getStores`,但在大多数情况下这是不必要的,因为你可以直接从 [`$app/stores`]($app-stores) 导入 `navigating` 和 `page`。如果你使用的是 Svelte 5 和 SvelteKit 2.12 或更高版本,请考虑改用 [`$app/state`]($app-state)。
¥You access them differently in SvelteKit. `stores` is now `getStores`, but in most cases it is unnecessary since you can import `navigating`, and `page` directly from [`$app/stores`]($app-stores). If you're on Svelte 5 and SvelteKit 2.12 or higher, consider using [`$app/state`]($app-state) instead.
### 路由(Routing)
¥Routing
不再支持正则表达式路由。而是使用 [高级路由匹配](advanced-routing#Matching)。
¥Regex routes are no longer supported. Instead, use [advanced route matching](advanced-routing#Matching).
### 片段(Segments)
¥Segments
以前,布局组件收到一个指示子段的 `segment` prop。这已被删除;你应该使用更灵活的 `$page.url.pathname`(或 `page.url.pathname`)值来派生你感兴趣的段。
¥Previously, layout components received a `segment` prop indicating the child segment. This has been removed; you should use the more flexible `$page.url.pathname` (or `page.url.pathname`) value to derive the segment you're interested in.
### URLs
在 Sapper 中,所有相对 URL 都是针对基本 URL(通常是 `/`,除非使用了 `basepath` 选项)而不是针对当前页面进行解析的。
¥In Sapper, all relative URLs were resolved against the base URL — usually `/`, unless the `basepath` option was used — rather than against the current page.
这会导致问题,但在 SvelteKit 中不再如此。相反,相对 URL 是根据当前页面(或 `load` 函数中的 `fetch` URL 的目标页面)解析的。在大多数情况下,使用根相对(即以 `/` 开头)URL 更容易,因为它们的含义不依赖于上下文。
¥This caused problems and is no longer the case in SvelteKit. Instead, relative URLs are resolved against the current page (or the destination page, for `fetch` URLs in `load` functions) instead. In most cases, it's easier to use root-relative (i.e. starts with `/`) URLs, since their meaning is not context-dependent.
### <a>属性(\<a> attributes)
¥\<a> attributes
* `sapper:prefetch` 现在是 `data-sveltekit-preload-data`
¥`sapper:prefetch` is now `data-sveltekit-preload-data`
* `sapper:noscroll` 现在是 `data-sveltekit-noscroll`
¥`sapper:noscroll` is now `data-sveltekit-noscroll`
## 端点(Endpoints)
¥Endpoints
在 Sapper 中,[服务器路由](routing#server) 接收 Node 的 `http` 模块(或 Polka 和 Express 等框架提供的增强版本)公开的 `req` 和 `res` 对象。
¥In Sapper, [server routes](routing#server) received the `req` and `res` objects exposed by Node's `http` module (or the augmented versions provided by frameworks like Polka and Express).
SvelteKit 的设计与应用的运行位置无关 - 它可以运行在 Node 服务器上,但也可以运行在无服务器平台或 Cloudflare Worker 中。因此,你不再直接与 `req` 和 `res` 交互。你的端点需要更新以匹配新签名。
¥SvelteKit is designed to be agnostic as to where the app is running — it could be running on a Node server, but could equally be running on a serverless platform or in a Cloudflare Worker. For that reason, you no longer interact directly with `req` and `res`. Your endpoints will need to be updated to match the new signature.
为了支持这种与环境无关的行为,`fetch` 现在在全局上下文中可用,因此你无需导入 `node-fetch`、`cross-fetch` 或类似的服务器端获取实现即可使用它。
¥To support this environment-agnostic behavior, `fetch` is now available in the global context, so you don't need to import `node-fetch`, `cross-fetch`, or similar server-side fetch implementations in order to use it.
## 集成(Integrations)
¥Integrations
有关集成的详细信息,请参阅 [integrations](./integrations)。
¥See [integrations](./integrations) for detailed information about integrations.
### HTML 压缩器(HTML minifier)
¥HTML minifier
Sapper 默认包含 `html-minifier`。SvelteKit 不包含此功能,但你可以将其添加为 prod 依赖,然后通过 [hook](hooks#Server-hooks-handle) 使用它:
¥Sapper includes `html-minifier` by default. SvelteKit does not include this, but you can add it as a prod dependency and then use it through a [hook](hooks#Server-hooks-handle):
```js
// @filename: ambient.d.ts
///
declare module 'html-minifier';
// @filename: index.js
// ---cut---
import { minify } from 'html-minifier';
import { building } from '$app/environment';
const minification_options = {
collapseBooleanAttributes: true,
collapseWhitespace: true,
conservativeCollapse: true,
decodeEntities: true,
html5: true,
ignoreCustomComments: [/^#/],
minifyCSS: true,
minifyJS: false,
removeAttributeQuotes: true,
removeComments: false, // some hydration code needs comments, so leave them in
removeOptionalTags: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
sortAttributes: true,
sortClassName: true
};
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
let page = '';
return resolve(event, {
transformPageChunk: ({ html, done }) => {
page += html;
if (done) {
return building ? minify(page, minification_options) : page;
}
}
});
}
```
请注意,使用 `vite preview` 测试站点的生产版本时,`prerendering` 是 `false`,因此要验证最小化的结果,你需要直接检查构建的 HTML 文件。
¥Note that `prerendering` is `false` when using `vite preview` to test the production build of the site, so to verify the results of minifying, you'll need to inspect the built HTML files directly.
# 其他资源
## FAQs
请参阅 [SvelteKit 常见问题](faq),了解常见问题的解决方案以及有用的提示和技巧。
¥Please see the [SvelteKit FAQ](faq) for solutions to common issues and helpful tips and tricks.
[Svelte 常见问题](../svelte/faq) 和 [`vite-plugin-svelte` FAQ](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md) 可能对从这些库中得出的问题也有帮助。
¥The [Svelte FAQ](../svelte/faq) and [`vite-plugin-svelte` FAQ](https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md) may also be helpful for questions deriving from those libraries.
## 示例(Examples)
¥Examples
我们编写并发布了几个不同的 SvelteKit 网站作为示例:
¥We've written and published a few different SvelteKit sites as examples:
* [`sveltejs/realworld`](https://github.com/sveltejs/realworld) 包含示例博客网站
¥[`sveltejs/realworld`](https://github.com/sveltejs/realworld) contains an example blog site
* [HackerNews 克隆](https://github.com/sveltejs/sites/tree/master/sites/hn.svelte.dev)
¥[A HackerNews clone](https://github.com/sveltejs/sites/tree/master/sites/hn.svelte.dev)
* [`svelte.dev`](https://github.com/sveltejs/svelte.dev)
SvelteKit 用户还在 GitHub 上的 [#sveltekit](https://github.com/topics/sveltekit) 和 [#sveltekit-template](https://github.com/topics/sveltekit-template) 主题以及 [Svelte Society 网站](https://sveltesociety.dev/templates?category=sveltekit) 上发布了大量示例。请注意,这些尚未经过维护人员的审查,可能不是最新的。
¥SvelteKit users have also published plenty of examples on GitHub, under the [#sveltekit](https://github.com/topics/sveltekit) and [#sveltekit-template](https://github.com/topics/sveltekit-template) topics, as well as on [the Svelte Society site](https://sveltesociety.dev/templates?category=sveltekit). Note that these have not been vetted by the maintainers and may not be up to date.
## 支持(Support)
¥Support
你可以在 [Discord](/chat) 和 [StackOverflow](https://stackoverflow.com/questions/tagged/sveltekit) 上寻求帮助。请首先在常见问题解答、Google 或其他搜索引擎、问题跟踪器和 Discord 聊天记录中搜索与你的问题相关的信息,以尊重他人的时间。提问的人比回答问题的人多得多,因此这将有助于让社区以可扩展的方式发展。
¥You can ask for help on [Discord](/chat) and [StackOverflow](https://stackoverflow.com/questions/tagged/sveltekit). Please first search for information related to your issue in the FAQ, Google or another search engine, issue tracker, and Discord chat history in order to be respectful of others' time. There are many more people asking questions than answering them, so this will help in allowing the community to grow in a scalable fashion.
# 词汇表
SvelteKit 的核心提供了高度可配置的渲染引擎。本节介绍了讨论渲染时使用的一些术语。上述文档提供了有关设置这些选项的参考。
¥The core of SvelteKit provides a highly configurable rendering engine. This section describes some of the terms used when discussing rendering. A reference for setting these options is provided in the documentation above.
## CSR
客户端渲染 (CSR) 是使用 JavaScript 在 Web 浏览器中生成页面内容。
¥Client-side rendering (CSR) is the generation of the page contents in the web browser using JavaScript.
在 SvelteKit 中,默认情况下将使用客户端渲染,但你可以使用 [`csr = false` 页面选项](page-options#csr) 关闭 JavaScript。
¥In SvelteKit, client-side rendering will be used by default, but you can turn off JavaScript with [the `csr = false` page option](page-options#csr).
## Hydration
Svelte 组件存储一些状态并在状态更新时更新 DOM。在 SSR 期间获取数据时,默认情况下 SvelteKit 将存储此数据并将其与服务器渲染的 HTML 一起传输到客户端。然后可以使用该数据在客户端上初始化组件,而无需再次调用相同的 API 端点。然后,Svelte 将检查 DOM 是否处于预期状态,并在称为 hydration 的过程中附加事件监听器。一旦组件完全水化,它们就可以像任何新创建的 Svelte 组件一样对其属性的变化做出反应。
¥Svelte components store some state and update the DOM when the state is updated. When fetching data during SSR, by default SvelteKit will store this data and transmit it to the client along with the server-rendered HTML. The components can then be initialized on the client with that data without having to call the same API endpoints again. Svelte will then check that the DOM is in the expected state and attach event listeners in a process called hydration. Once the components are fully hydrated, they can react to changes to their properties just like any newly created Svelte component.
在 SvelteKit 中,页面将默认进行水化,但你可以使用 [`csr = false` 页面选项](page-options#csr) 关闭 JavaScript。
¥In SvelteKit, pages will be hydrated by default, but you can turn off JavaScript with [the `csr = false` page option](page-options#csr).
## 预渲染(Prerendering)
¥Prerendering
预渲染意味着在构建时计算页面的内容并保存 HTML 以供显示。这种方法具有与传统服务器渲染页面相同的好处,但避免为每个访问者重新计算页面,因此随着访问者数量的增加几乎可以免费扩展。权衡是构建过程更昂贵,并且只能通过构建和部署新版本的应用来更新预渲染的内容。
¥Prerendering means computing the contents of a page at build time and saving the HTML for display. This approach has the same benefits as traditional server-rendered pages, but avoids recomputing the page for each visitor and so scales nearly for free as the number of visitors increases. The tradeoff is that the build process is more expensive and prerendered content can only be updated by building and deploying a new version of the application.
但并非所有导航都会导致错误,例如,如果下一页的 JavaScript 已加载。基本规则如下:要使内容可预渲染,任何两个直接访问该内容的用户都必须从服务器获取相同的内容,并且页面不得包含 [actions](form-actions)。请注意,只要所有用户都会看到相同的预渲染内容,你仍然可以预渲染基于页面参数加载的内容。
¥Not all pages can be prerendered. The basic rule is this: for content to be prerenderable, any two users hitting it directly must get the same content from the server, and the page must not contain [actions](form-actions). Note that you can still prerender content that is loaded based on the page's parameters as long as all users will be seeing the same prerendered content.
预渲染页面不仅限于静态内容。如果在客户端获取和渲染用户特定数据,你可以构建个性化页面。但需要注意的是,如上所述,如果不对该内容执行 SSR,你将遇到一些不利因素。
¥Pre-rendered pages are not limited to static content. You can build personalized pages if user-specific data is fetched and rendered client-side. This is subject to the caveat that you will experience the downsides of not doing SSR for that content as discussed above.
在 SvelteKit 中,你可以使用 `svelte.config.js` 中的 [`prerender` 页面选项](page-options#prerender) 和 [`prerender` 配置](configuration#prerender) 控制预渲染。
¥In SvelteKit, you can control prerendering with [the `prerender` page option](page-options#prerender) and [`prerender` config](configuration#prerender) in `svelte.config.js`.
## 路由(Routing)
¥Routing
默认情况下,当你导航到新页面时(通过单击链接或使用浏览器的前进或后退按钮),SvelteKit 将拦截尝试的导航并处理它,而不是允许浏览器向服务器发送目标页面的请求。SvelteKit 随后将通过渲染新页面的组件来更新客户端上显示的内容,而新页面又可以调用必要的 API 端点。响应尝试导航而更新客户端上的页面的过程称为客户端路由。
¥By default, when you navigate to a new page (by clicking on a link or using the browser's forward or back buttons), SvelteKit will intercept the attempted navigation and handle it instead of allowing the browser to send a request to the server for the destination page. SvelteKit will then update the displayed contents on the client by rendering the component for the new page, which in turn can make calls to the necessary API endpoints. This process of updating the page on the client in response to attempted navigation is called client-side routing.
在 SvelteKit 中,默认情况下将使用客户端路由,但你可以使用 [`data-sveltekit-reload`](link-options#data-sveltekit-reload) 跳过它。
¥In SvelteKit, client-side routing will be used by default, but you can skip it with [`data-sveltekit-reload`](link-options#data-sveltekit-reload).
## SPA
单页应用 (SPA) 是一种应用,其中对服务器的所有请求都会加载单个 HTML 文件,然后该文件根据请求的 URL 对请求的内容进行客户端渲染。所有导航都在客户端处理,这个过程称为客户端路由,每个页面的内容都会更新,而常见的布局元素基本保持不变。SPA 不提供 SSR,它具有上述缺点。但是,有些应用不会受到这些缺点的很大影响,例如登录背后的复杂业务应用,其中 SEO 并不重要,并且已知用户将从一致的计算环境访问该应用。
¥A single-page app (SPA) is an application in which all requests to the server load a single HTML file which then does client-side rendering of the requested contents based on the requested URL. All navigation is handled on the client-side in a process called client-side routing with per-page contents being updated and common layout elements remaining largely unchanged. SPAs do not provide SSR, which has the shortcoming described above. However, some applications are not greatly impacted by these shortcomings such as a complex business application behind a login where SEO would not be important and it is known that users will be accessing the application from a consistent computing environment.
在 SvelteKit 中,你可以使用 [使用 `adapter-static` 构建 SPA](single-page-apps)。
¥In SvelteKit, you can [build an SPA with `adapter-static`](single-page-apps).
## SSG
静态站点生成 (SSG) 是指每个页面都经过预渲染的站点。SvelteKit 并非像某些工具那样只用于静态站点生成,因此可能无法像专门为此目的构建的工具那样有效地扩展以有效地渲染大量页面。但是,与大多数专用 SSG 相比,SvelteKit 确实可以很好地允许在不同的页面上混合和匹配不同的渲染类型。完全预渲染站点的一个好处是你不需要维护或支付服务器来执行 SSR。一旦生成,站点就可以从 CDN 提供服务,从而实现出色的 "第一个字节的时间" 性能。这种交付模型通常称为 JAMstack。
¥Static Site Generation (SSG) is a term that refers to a site where every page is prerendered. SvelteKit was not built to do only static site generation like some tools and so may not scale as well to efficiently render a very large number of pages as tools built specifically for that purpose. However, in contrast to most purpose-built SSGs, SvelteKit does nicely allow for mixing and matching different rendering types on different pages. One benefit of fully prerendering a site is that you do not need to maintain or pay for servers to perform SSR. Once generated, the site can be served from CDNs, leading to great "time to first byte" performance. This delivery model is often referred to as JAMstack.
在 SvelteKit 中,你可以使用 [`adapter-static`](adapter-static) 进行静态站点生成,或者通过在 `svelte.config.js` 中使用 [`prerender` 页面选项](page-options#prerender) 或 [`prerender` 配置](configuration#prerender) 配置每个页面进行预渲染。
¥In SvelteKit, you can do static site generation by using [`adapter-static`](adapter-static) or by configuring every page to be prerendered using [the `prerender` page option](page-options#prerender) or [`prerender` config](configuration#prerender) in `svelte.config.js`.
## SSR
服务器端渲染 (SSR) 是在服务器上生成页面内容。SSR 通常是 SEO 的首选。虽然有些搜索引擎可以索引在客户端动态生成的内容,但即使在这些情况下也可能需要更长的时间。它还倾向于提高感知性能,并在 JavaScript 失败或被禁用([比你想象的更频繁](https://kryogenix.org/code/browser/everyonehasjs.html) 会发生这种情况)时让用户能够访问你的应用。
¥Server-side rendering (SSR) is the generation of the page contents on the server. SSR is generally preferred for SEO. While some search engines can index content that is dynamically generated on the client-side it may take longer even in these cases. It also tends to improve perceived performance and makes your app accessible to users if JavaScript fails or is disabled (which happens [more often than you probably think](https://kryogenix.org/code/browser/everyonehasjs.html)).
在 SvelteKit 中,页面默认在服务器端渲染。你可以使用 [`ssr` 页面选项](page-options#ssr) 禁用 SSR。
¥In SvelteKit, pages are server-side rendered by default. You can disable SSR with [the `ssr` page option](page-options#ssr).
# @sveltejs/kit
```js
// @noErrors
import {
Server,
VERSION,
error,
fail,
isActionFailure,
isHttpError,
isRedirect,
json,
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.
```dts
function fail(status: number): ActionFailure;
```
```dts
function fail<
T extends Record | undefined = undefined
>(status: number, data: T): ActionFailure;
```
## 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 | undefined
): 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;
```
## json
从提供的数据创建 JSON `Response` 对象。
¥Create a JSON `Response` object from the supplied data.
```dts
function json(
data: any,
init?: ResponseInit | undefined
): Response;
```
## 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.
```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 | undefined
): 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 Partial
> = Partial<
Record
>,
OutputData extends Record | void = Record<
string,
any
> | void,
RouteId extends string | null = string | null
> = (
event: RequestEvent
) => MaybePromise;
```
## ActionFailure
```dts
interface ActionFailure<
T extends Record
| undefined = undefined
> {/*…*/}
```
```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 ` ` with a GET method
* `leave`:用户通过关闭选项卡或使用后退/前进按钮转到其他文档来离开应用
¥`leave`: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document
* `link`:导航由链接单击触发
¥`link`: Navigation was triggered by a link click
* `goto`:导航由 `goto(...)` 调用或重定向触发
¥`goto`: Navigation was triggered by a `goto(...)` call or a redirect
* `popstate`:导航由后退/前进导航触发
¥`popstate`: Navigation was triggered by back/forward navigation
```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
interface OnNavigate extends Navigation {/*…*/}
```
```dts
type: Exclude
;
```
导航类型:
¥The type of navigation:
* `form`:用户提交了 `
`
¥`form`: The user submitted a ` `
* `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
willUnload: false;
```
由于 `onNavigate` 回调是在客户端导航之前立即调用的,因此它们永远不会在卸载页面的导航中被调用。
¥Since `onNavigate` callbacks are called immediately before a client-side navigation, they will never be called with a navigation that unloads the page.
## 页面(Page)
¥Page
`$page` 存储的形状
¥The shape of the `$page` store
```dts
interface Page<
Params extends Record
= Record<
string,
string
>,
RouteId extends string | null = string | null
> {/*…*/}
```
```dts
url: URL;
```
当前页面的 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]`
¥The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`
```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://web.nodejs.cn/en-US/docs/Web/HTTP/Status#redirection_messages),在 300-308 范围内。
¥The [HTTP status code](https://web.nodejs.cn/en-US/docs/Web/HTTP/Status#redirection_messages), in the range 300-308.
```dts
location: string;
```
重定向到的位置。
¥The location to redirect to.
## RequestEvent
```dts
interface RequestEvent<
Params extends Partial
> = Partial<
Record
>,
RouteId extends string | null = string | null
> {/*…*/}
```
```dts
cookies: Cookies;
```
获取或设置与当前请求相关的 cookie
¥Get or set cookies related to the current request
```dts
fetch: typeof fetch;
```
`fetch` 等同于 [原生 `fetch` Web API](https://web.nodejs.cn/en-US/docs/Web/API/fetch),但具有一些附加功能:
¥`fetch` is equivalent to the [native `fetch` web API](https://web.nodejs.cn/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]`
¥The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`
```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.
## 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 Partial
> = Partial<
Record
>,
RouteId extends string | null = string | 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 }) => void | string;
```
## 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
mimeTypes: Record
;
```
```dts
_: {/*…*/}
```
将代码放在靠近使用位置的位置
¥private fields
```dts
client: NonNullable
;
```
```dts
nodes: SSRNodeLoader[];
```
```dts
routes: SSRRoute[];
```
```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) => ReadableStream;
```
将资源文件名转换为 `ReadableStream` 的函数。需要 `$app/server` 中的 `read` 导出才能正常工作
¥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 Partial
> = Partial<
Record
>,
ParentData extends Record = Record<
string,
any
>,
OutputData extends Record | void = Record<
string,
any
> | void,
RouteId extends string | null = string | null
> = (
event: ServerLoadEvent
) => MaybePromise;
```
## ServerLoadEvent
```dts
interface ServerLoadEvent<
Params extends Partial
> = Partial<
Record
>,
ParentData extends Record = Record<
string,
any
>,
RouteId extends string | null = string | 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://web.nodejs.cn/en-US/docs/Glossary/percent-encoding)。
¥URLs can be absolute or relative to the page being loaded, and must be [encoded](https://web.nodejs.cn/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!' };
}
}
```
## 快照(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;
}) => void)
>;
```
## 传输(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;
```
## 私有类型(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';
```
## 预渲染(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: import('@sveltejs/kit').Handle[]
): import('@sveltejs/kit').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.
```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,
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;
state?: App.PageState | undefined;
}
| 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;
```
## 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 { assets, base, resolveRoute } from '$app/paths';
```
## assets
与 [`config.kit.paths.assets`](/docs/kit/configuration#paths) 匹配的绝对路径。
¥An absolute path that matches [`config.kit.paths.assets`](/docs/kit/configuration#paths).
> [!NOTE] 如果指定了 `config.kit.paths.assets` 的值,它将在 `vite dev` 或 `vite preview` 期间被替换为 `'/_svelte_kit_assets'`,因为资源尚未存在于其最终 URL 中。
>
> ¥[!NOTE] If a value for `config.kit.paths.assets` is specified, it will be replaced with `'/_svelte_kit_assets'` during `vite dev` or `vite preview`, since the assets don't yet live at their eventual URL.
```dts
let assets:
| ''
| `https://${string}`
| `http://${string}`
| '/_svelte_kit_assets';
```
## base
与 [`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}`;
```
## resolveRoute
使用参数填充路由 ID 以解析路径名。
¥Populate a route ID with params to resolve a pathname.
```js
// @errors: 7031
import { resolveRoute } from '$app/paths';
resolveRoute(
`/blog/[slug]/[...somethingElse]`,
{
slug: 'hello-world',
somethingElse: 'something/else'
}
); // `/blog/hello-world/something/else`
```
```dts
function resolveRoute(
id: string,
params: Record
): string;
```
# $app/server
```js
// @noErrors
import { read } from '$app/server';
```
## 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;
```
# $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`.
> [!NOTE] 此模块已在 2.12 中添加。如果你使用的是 SvelteKit 的早期版本,请改用 [`$app/stores`]($app-stores)。
>
> ¥[!NOTE]
> This module was added in 2.12. If you're using an earlier version of SvelteKit, use [`$app/stores`]($app-stores) instead.
```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}
```
在服务器上,只能在渲染期间读取值(换句话说,不能在 `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;
};
```
# $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.
预渲染期间不能使用动态环境变量。
¥Dynamic environment variables cannot be used during prerendering.
```ts
import { env } from '$env/dynamic/private';
console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE);
```
> 在 `dev` 中,`$env/dynamic` 始终包含来自 `.env` 的环境变量。在 `prod` 中,此行为取决于你的适配器。
>
> ¥In `dev`, `$env/dynamic` always includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter.
# $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.
预渲染期间不能使用动态环境变量。
¥Dynamic environment variables cannot be used during prerendering.
```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:
```bash
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) 自定义从 `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)
```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
```dts
interface Config {/*…*/}
```
```dts
compilerOptions?: CompileOptions;
```
* 默认 `{}`
¥default `{}`
传递给 [`svelte.compile`](/docs/svelte/svelte-compiler#CompileOptions) 的选项。
¥Options passed to [`svelte.compile`](/docs/svelte/svelte-compiler#CompileOptions).
```dts
extensions?: string[];
```
* 默认 `[".svelte"]`
¥default `[".svelte"]`
应视为 Svelte 文件的文件扩展名列表。
¥List of file extensions that should be treated as Svelte files.
```dts
kit?: KitConfig;
```
SvelteKit 选项
¥SvelteKit options
```dts
preprocess?: any;
```
预处理器选项(如果有)。也可以通过 Vite 的预处理器功能进行预处理。
¥Preprocessor options, if any. Preprocessing can alternatively also be done through Vite's preprocessor capabilities.
```dts
vitePlugin?: PluginOptions;
```
`vite-plugin-svelte` 插件选项。
¥`vite-plugin-svelte` plugin 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/*'
}
}
};
```
> [!NOTE] 内置的 `$lib` 别名由 `config.kit.files.lib` 控制,因为它用于打包。
>
> ¥[!NOTE] The built-in `$lib` alias is controlled by `config.kit.files.lib` as it is used for packaging.
> [!NOTE] 你需要运行 `npm run dev` 才能让 SvelteKit 在 `jsconfig.json` 或 `tsconfig.json` 中自动生成所需的别名配置。
>
> ¥[!NOTE] You will need to run `npm run dev` to have SvelteKit automatically generate the required alias configuration in `jsconfig.json` or `tsconfig.json`.
## 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://web.nodejs.cn/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) 配置。CSP 通过限制可以从中加载资源的位置,帮助保护你的用户免受跨站点脚本 (XSS) 攻击。例如,像这样的配置...
¥[Content Security Policy](https://web.nodejs.cn/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%`(例如 `
```
如果你将 `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]/+page.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 PageServerLoad = Kit.ServerLoad;
export type PageLoad = Kit.Load;
```
由于 TypeScript 配置中的 [`rootDirs`](https://ts.nodejs.cn/tsconfig#rootDirs) 选项,这些文件可以作为同级文件导入到你的端点和页面中:
¥These files can be imported into your endpoints and pages as siblings, thanks to the [`rootDirs`](https://ts.nodejs.cn/tsconfig#rootDirs) option in your TypeScript configuration:
```js
/// file: src/routes/[foo]/[bar]/[baz]/+page.server.js
// @filename: $types.d.ts
import type * as Kit from '@sveltejs/kit';
type RouteParams = {
foo: string;
bar: string;
baz: string;
}
export type PageServerLoad = Kit.ServerLoad;
// @filename: index.js
// @errors: 2355
// ---cut---
/** @type {import('./$types').PageServerLoad} */
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 }) {
// ...
}
```
> [!NOTE] 为了实现这一点,你自己的 `tsconfig.json` 或 `jsconfig.json` 应该从生成的 `.svelte-kit/tsconfig.json` 扩展(其中 `.svelte-kit` 是你的 [`outDir`](configuration#outDir)):
>
> ¥[!NOTE] For this to work, your own `tsconfig.json` or `jsconfig.json` should extend from the generated `.svelte-kit/tsconfig.json` (where `.svelte-kit` is your [`outDir`](configuration#outDir)):
>
> `{ "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": {
"baseUrl": "..",
"paths": {
"$lib": "src/lib",
"$lib/*": "src/lib/*"
},
"rootDirs": ["..", "./types"]
},
"include": ["../src/**/*.js", "../src/**/*.ts", "../src/**/*.svelte"],
"exclude": ["../node_modules/**", "./**"]
}
```
其他内容是 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-preprocess cannot
// otherwise compile components correctly
"importsNotUsedAsValues": "error",
// Vite compiles one TypeScript module
// at a time, rather than compiling
// the entire module graph
"isolatedModules": true,
// TypeScript cannot 'see' when you
// use an imported value in your
// markup, so we need this
"preserveValueImports": true,
// This ensures both `vite build`
// and `svelte-package` work correctly
"lib": ["esnext", "DOM", "DOM.Iterable"],
"moduleResolution": "node",
"module": "esnext",
"target": "esnext"
}
}
```
## $lib
这是 `src/lib` 的简单别名,或指定为 [`config.kit.files.lib`](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 the 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://npm.nodejs.cn/cli/v8/commands/npx)(或者如果你使用的是其他包管理器,则使用等效命令 - 例如,如果你使用的是 [pnpm](https://pnpm.nodejs.cn/),则使用 `pnpx`):
¥The easiest way to run `sv` is with [`npx`](https://npm.nodejs.cn/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.nodejs.cn/)):
```bash
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 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
```bash
npx sv create [options] [path]
```
## 选项(Options)
¥Options
### `--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://ts.nodejs.cn/docs/handbook/jsdoc-supported-types.html)
¥`jsdoc` — use [JSDoc syntax](https://ts.nodejs.cn/docs/handbook/jsdoc-supported-types.html) for types
### `--no-types`
防止添加类型检查。不推荐!
¥Prevent typechecking from being added. Not recommended!
### `--no-add-ons`
在没有交互式附加组件提示的情况下运行命令
¥Run the command without the interactive add-ons prompt
### `--no-install`
跳过依赖安装
¥Skip dependency installation
# sv add
`sv add` 将其统一为一个语法概念,该概念主要依赖于常规 JavaScript 解构语法。
¥`sv add` updates an existing project with new functionality.
## 用法(Usage)
¥Usage
```bash
npx sv add
```
```bash
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) 项目根目录的路径
¥`-C`, `--cwd` — path to the root of your Svelte(Kit) project
* `--no-preconditions` — 跳过检查先决条件
¥`--no-preconditions` — skip checking preconditions
* `--no-install` — 跳过依赖安装
¥`--no-install` — skip dependency installation
## 官方附加组件(Official add-ons)
¥Official add-ons
* `drizzle`
* `eslint`
* `sveltekit-adapter`
* `lucia`
* `mdsvex`
* `paraglide`
* `playwright`
* `prettier`
* `storybook`
* `tailwindcss`
* `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:
```bash
npm i -D svelte-check
```
## 用法(Usage)
¥Usage
```bash
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:
```bash
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`:
```bash
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:
```bash
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 argoument.
如果参数是 `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
```bash
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.