` 不再是必需的。
¥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).
## Edge
边缘渲染是指在靠近用户的内容交付网络 (CDN) 中渲染应用。边缘渲染允许页面的请求和响应传输更短的距离,从而改善延迟。
¥Rendering on the edge refers to rendering an application in a content delivery network (CDN) near the user. Edge rendering allows the request and response for a page to travel a shorter distance thus improving latency.
## 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).
## ISR
增量静态再生 (ISR) 允许你在访问者请求这些页面时在你的网站上生成静态页面,而无需重新部署。与具有大量页面的 [SSG](#SSG) 站点相比,这可能会减少构建时间。你可以执行 [使用 `adapter-vercel` 的 ISR](adapter-vercel#Incremental-Static-Regeneration)。
¥Incremental static regeneration (ISR) allows you to generate static pages on your site as visitors request those pages without redeploying. This may reduces build times compared to [SSG](#SSG) sites with a large number of pages. You can do [ISR with `adapter-vercel`](adapter-vercel#Incremental-Static-Regeneration).
## MPA
在服务器上渲染每个页面视图的传统应用(例如使用 JavaScript 以外的语言编写的应用)通常被称为多页应用 (MPA)。
¥Traditional applications that render each page view on the server — such as those written in languages other than JavaScript — are often referred to as multi-page apps (MPA).
## 预渲染(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`.
## PWA
渐进式 Web 应用 (PWA) 是使用 Web API 和技术构建的应用,但功能类似于移动或桌面应用。网站充当 [可以安装 PWA](https://web.dev/learn/pwa/installation),允许你在启动器、主屏幕或开始菜单上向应用添加快捷方式。许多 PWA 将利用 [服务工作者](service-workers) 来构建离线功能。
¥A progressive web app (PWA) is an app that's built using web APIs and technologies, but functions like a mobile or desktop app. Sites served as [PWAs can be installed](https://web.dev/learn/pwa/installation), allowing you to add a shortcut to the application on your launcher, home screen, or start menu. Many PWAs will utilize [service workers](service-workers) to build offline capabilities.
## 路由(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 特性较差。但是,有些应用不会受到这些缺点的很大影响,例如登录背后的复杂业务应用,其中 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 and thus have worse performance and SEO characteristics. 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) 是指每个页面都经过预渲染的站点。完全预渲染站点的一个好处是你不需要维护或支付服务器来执行 SSR。生成后,该站点可以从 CDN 提供服务,从而实现出色的“第一个字节时间”性能。这种交付模型通常称为 JAMstack。
¥Static Site Generation (SSG) is a term that refers to a site where every page is prerendered. 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,
normalizeUrl,
redirect,
text
} from '@sveltejs/kit';
```
## 服务器(Server)
¥Server
```dts
class Server {/*…*/}
```
```dts
constructor(manifest: SSRManifest);
```
```dts
init(options: ServerInitOptions): Promise
;
```
```dts
respond(request: Request, options: RequestOptions): Promise
;
```
## VERSION
```dts
const VERSION: string;
```
## error
抛出带有 HTTP 状态代码和可选消息的错误。在请求处理期间调用时,这将导致 SvelteKit 返回错误响应而不调用 `handleError`。确保你没有捕获抛出的错误,否则会阻止 SvelteKit 处理它。
¥Throws an error with a HTTP status code and an optional message.
When called during request handling, this will cause SvelteKit to
return an error response without invoking `handleError`.
Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.
```dts
function error(status: number, body: App.Error): never;
```
```dts
function error(
status: number,
body?: {
message: string;
} extends App.Error
? App.Error | string | undefined
: never
): never;
```
## fail
创建 `ActionFailure` 对象。表单提交失败时调用。
¥Create an `ActionFailure` object. Call when form submission fails.
```dts
function fail(status: number): ActionFailure;
```
```dts
function fail<
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;
```
## normalizeUrl
自发布起可用 2.18.0
¥Available since 2.18.0
从 URL 路径名中删除可能的 SvelteKit 内部后缀和尾随斜杠。返回规范化的 URL 以及基于新路径名(可能包括搜索)或 URL 添加回潜在后缀的方法。
¥Strips possible SvelteKit-internal suffixes and trailing slashes from the URL pathname.
Returns the normalized URL as well as a method for adding the potential suffix back
based on a new pathname (possibly including search) or URL.
```js
// @errors: 7031
import { normalizeUrl } from '@sveltejs/kit';
const { url, denormalize } = normalizeUrl('/blog/post/__data.json');
console.log(url.pathname); // /blog/post
console.log(denormalize('/blog/post/a')); // /blog/post/a/__data.json
```
```dts
function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: string | URL) => URL;
};
```
## redirect
重定向请求。在请求处理期间调用时,SvelteKit 将返回重定向响应。确保你没有捕获抛出的重定向,否则会阻止 SvelteKit 处理它。
¥Redirect a request. When called during request handling, SvelteKit will return a redirect response.
Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
最常见的状态代码:
¥Most common status codes:
* `303 See Other`:重定向为 GET 请求(通常在表单 POST 请求后使用)
¥`303 See Other`: redirect as a GET request (often used after a form POST request)
* `307 Temporary Redirect`:重定向将保留请求方法
¥`307 Temporary Redirect`: redirect will keep the request method
* `308 Permanent Redirect`:重定向将保留请求方法,SEO 将转移到新页面
¥`308 Permanent Redirect`: redirect will keep the request method, SEO will be transferred to the new page
[查看所有重定向状态代码](https://web.nodejs.cn/en-US/docs/Web/HTTP/Status#redirection_messages)
¥[See all redirect status codes](https://web.nodejs.cn/en-US/docs/Web/HTTP/Status#redirection_messages)
```dts
function redirect(
status:
| 300
| 301
| 302
| 303
| 304
| 305
| 306
| 307
| 308
| ({} & number),
location: string | URL
): never;
```
## text
从提供的主体创建 `Response` 对象。
¥Create a `Response` object from the supplied body.
```dts
function text(
body: string,
init?: ResponseInit | 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`](/docs/kit/$app-state#page) 反应对象和 [`$page`](/docs/kit/$app-stores) 存储的形状。
¥The shape of the [`page`](/docs/kit/$app-state#page) reactive object and the [`$page`](/docs/kit/$app-stores) store.
```dts
interface Page<
Params extends 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]`。当没有匹配的路由时,它是 `null`。
¥The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`. It is `null` when no route is matched.
```dts
status: number;
```
当前页面的 HTTP 状态代码。
¥HTTP status code of the current page.
```dts
error: App.Error | null;
```
当前页面的错误对象(如果有)。从 `handleError` 钩子填充。
¥The error object of the current page, if any. Filled from the `handleError` hooks.
```dts
data: App.PageData & Record
;
```
当前页面上所有 `load` 函数的所有数据的合并结果。你可以通过 `App.PageData` 输入公分母。
¥The merged result of all data from all `load` functions on the current page. You can type a common denominator through `App.PageData`.
```dts
state: App.PageState;
```
页面状态,可以使用 `$app/navigation` 中的 [`pushState`](/docs/kit/$app-navigation#pushState) 和 [`replaceState`](/docs/kit/$app-navigation#replaceState) 函数进行操作。
¥The page state, which can be manipulated using the [`pushState`](/docs/kit/$app-navigation#pushState) and [`replaceState`](/docs/kit/$app-navigation#replaceState) functions from `$app/navigation`.
```dts
form: any;
```
仅在表单提交后填充。有关更多信息,请参阅 [表单操作](/docs/kit/form-actions)。
¥Filled only after a form submission. See [form actions](/docs/kit/form-actions) for more info.
## ParamMatcher
参数匹配器的形状。有关更多信息,请参阅 [matching](/docs/kit/advanced-routing#Matching)。
¥The shape of a param matcher. See [matching](/docs/kit/advanced-routing#Matching) for more info.
```dts
type ParamMatcher = (param: string) => boolean;
```
## PrerenderOption
```dts
type PrerenderOption = boolean | 'auto';
```
## 重定向(Redirect)
¥Redirect
[`redirect`](/docs/kit/@sveltejs-kit#redirect) 函数返回的对象。
¥The object returned by the [`redirect`](/docs/kit/@sveltejs-kit#redirect) function.
```dts
interface Redirect {/*…*/}
```
```dts
status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;
```
[HTTP 状态代码](https://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]`。当没有匹配的路由时,它是 `null`。
¥The ID of the current route - e.g. for `src/routes/blog/[slug]`, it would be `/blog/[slug]`. It is `null` when no route is matched.
```dts
setHeaders: (headers: Record
) => void;
```
如果你需要为响应设置标头,则可以使用此方法进行设置。如果你希望缓存页面,这将非常有用,例如:
¥If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:
```js
// @errors: 7031
/// file: src/routes/blog/+page.js
export async function load({ fetch, setHeaders }) {
const url = `https://cms.example.com/articles.json`;
const response = await fetch(url);
setHeaders({
age: response.headers.get('age'),
'cache-control': response.headers.get('cache-control')
});
return response.json();
}
```
多次设置相同的标头(即使在单独的 `load` 函数中)是错误的 - 你只能设置一次给定的标头。
¥Setting the same header multiple times (even in separate `load` functions) is an error — you can only set a given header once.
你不能使用 `setHeaders` 添加 `set-cookie` 标头 — 改用 [`cookies`](/docs/kit/@sveltejs-kit#Cookies) API。
¥You cannot add a `set-cookie` header with `setHeaders` — use the [`cookies`](/docs/kit/@sveltejs-kit#Cookies) API instead.
```dts
url: URL;
```
请求的 URL。
¥The requested URL.
```dts
isDataRequest: boolean;
```
如果请求来自请求 `+page/layout.server.js` 数据的客户端,则为 `true`。在这种情况下,`url` 属性将被剥离与数据请求相关的内部信息。如果区别对你很重要,请改用此属性。
¥`true` if the request comes from the client asking for `+page/layout.server.js` data. The `url` property will be stripped of the internal information
related to the data request in this case. Use this property instead if the distinction is important to you.
```dts
isSubRequest: boolean;
```
`true` 用于来自 SvelteKit 的 `+server.js` 调用,而无需实际发出 HTTP 请求的开销。当你在服务器上发出同源 `fetch` 请求时,就会发生这种情况。
¥`true` for `+server.js` calls coming from SvelteKit without the overhead of actually making an HTTP request. This happens when you make same-origin `fetch` requests on the server.
## 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;
fetch: typeof fetch;
}) => MaybePromise;
```
## ResolveOptions
```dts
interface ResolveOptions {/*…*/}
```
```dts
transformPageChunk?: (input: { html: string; done: boolean }) => MaybePromise
;
```
* `input` html 块和信息(如果这是最后一个块)
¥`input` the html chunk and the info if this is the last chunk
将自定义转换应用于 HTML。如果 `done` 为真,则它是最终块。块不能保证是格式正确的 HTML(例如,它们可能包含元素的开始标记但不包含结束标记),但它们始终会在合理的边界处进行拆分,例如 `%sveltekit.head%` 或布局/页面组件。
¥Applies custom transforms to HTML. If `done` is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML
(they could include an element's opening tag but not its closing tag, for example)
but they will always be split at sensible boundaries such as `%sveltekit.head%` or layout/page components.
```dts
filterSerializedResponseHeaders?: (name: string, value: string) => boolean;
```
* `name` 标头名称
¥`name` header name
* `value` 标头值
¥`value` header value
确定当 `load` 函数使用 `fetch` 加载资源时,应在序列化响应中包含哪些标头。默认情况下,不会包含任何内容。
¥Determines which headers should be included in serialized responses when a `load` function loads a resource with `fetch`.
By default, none will be included.
```dts
preload?: (input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }) => boolean;
```
* `input` 文件的类型及其路径
¥`input` the type of the file and its path
确定应将什么添加到 `` 标签以预加载它。默认情况下,`js` 和 `css` 文件将被预加载。
¥Determines what should be added to the `` tag to preload it.
By default, `js` and `css` files will be preloaded.
## RouteDefinition
```dts
interface RouteDefinition
{/*…*/}
```
```dts
api: {
methods: Array
;
};
```
```dts
page: {
methods: Array
>;
};
```
```dts
pattern: RegExp;
```
```dts
prerender: PrerenderOption;
```
```dts
segments: RouteSegment[];
```
```dts
methods: Array
;
```
```dts
config: Config;
```
## SSRManifest
```dts
interface SSRManifest {/*…*/}
```
```dts
appDir: string;
```
```dts
appPath: string;
```
```dts
assets: Set
;
```
来自 `kit.config.files.assets` 和服务工作者(如果有)的静态文件。
¥Static files from `kit.config.files.assets` and the service worker (if any).
```dts
mimeTypes: Record
;
```
```dts
_: {/*…*/}
```
将代码放在靠近使用位置的位置
¥private fields
```dts
client: NonNullable
;
```
```dts
nodes: SSRNodeLoader[];
```
```dts
routes: SSRRoute[];
```
```dts
prerendered_routes: Set
;
```
```dts
matchers: () => Promise
>;
```
```dts
server_assets: Record
;
```
服务器代码导入的所有资源的 `[file]: size` 映射。
¥A `[file]: size` map of all assets imported by server code.
## ServerInit
自 2.10.0 起可用
¥Available since 2.10.0
在服务器响应其第一个请求之前将调用 [`init`](/docs/kit/hooks#Shared-hooks-init)
¥The [`init`](/docs/kit/hooks#Shared-hooks-init) will be invoked before the server responds to its first request
```dts
type ServerInit = () => MaybePromise;
```
## ServerInitOptions
```dts
interface ServerInitOptions {/*…*/}
```
```dts
env: Record
;
```
环境变量映射。
¥A map of environment variables.
```dts
read?: (file: string) => ReadableStream;
```
将资源文件名转换为 `ReadableStream` 的函数。`read` 从 `$app/server` 导出需要此设置才能正常工作。
¥A function that turns an asset filename into a `ReadableStream`. Required for the `read` export from `$app/server` to work.
## ServerLoad
`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;
}) => MaybePromise)
>;
```
## 传输(Transport)
¥Transport
自 2.11.0 起可用
¥Available since 2.11.0
[`transport`](/docs/kit/hooks#Universal-hooks-transport) 钩子允许你跨服务器/客户端边界传输自定义类型。
¥The [`transport`](/docs/kit/hooks#Universal-hooks-transport) hook allows you to transport custom types across the server/client boundary.
每个传输器都有一对 `encode` 和 `decode` 函数。在服务器上,`encode` 判断某个值是否是自定义类型的实例,如果是,则返回该值的非错误编码,该编码可以是对象或数组(否则返回 `false`)。
¥Each transporter has a pair of `encode` and `decode` functions. On the server, `encode` determines whether a value is an instance of the custom type and, if so, returns a non-falsy encoding of the value which can be an object or an array (or `false` otherwise).
在浏览器中,`decode` 会将编码转换回自定义类型的实例。
¥In the browser, `decode` turns the encoding back into an instance of the custom type.
```ts
import type { Transport } from '@sveltejs/kit';
declare class MyCustomType {
data: any
}
// hooks.js
export const transport: Transport = {
MyCustomType: {
encode: (value) => value instanceof MyCustomType && [value.data],
decode: ([data]) => new MyCustomType(data)
}
};
```
```dts
type Transport = Record;
```
## 传输器(Transporter)
¥Transporter
[`transport`](/docs/kit/hooks#Universal-hooks-transport) 钩子的成员。
¥A member of the [`transport`](/docs/kit/hooks#Universal-hooks-transport) hook.
```dts
interface Transporter<
T = any,
U = Exclude<
any,
false | 0 | '' | null | undefined | typeof NaN
>
> {/*…*/}
```
```dts
encode: (value: T) => false | U;
```
```dts
decode: (data: U) => T;
```
## 私有类型(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.
It accepts an options object
* 如果你不希望 ` ` 值在提交成功后被重置,请使用 `reset: false`
¥`reset: false` if you don't want the ` ` values to be reset after a successful submission
* 如果你不希望操作在提交后调用 `invalidateAll`,请使用 `invalidateAll: false`
¥`invalidateAll: false` if you don't want the action to call `invalidateAll` after submission
```dts
function enhance<
Success extends Record | undefined,
Failure extends Record | undefined
>(
form_element: HTMLFormElement,
submit?: import('@sveltejs/kit').SubmitFunction<
Success,
Failure
>
): {
destroy(): void;
};
```
# $app/navigation
```js
// @noErrors
import {
afterNavigate,
beforeNavigate,
disableScrollHandling,
goto,
invalidate,
invalidateAll,
onNavigate,
preloadCode,
preloadData,
pushState,
replaceState
} from '$app/navigation';
```
## afterNavigate
当前组件挂载时以及我们导航到 URL 时运行提供的 `callback` 的生命周期函数。
¥A lifecycle function that runs the supplied `callback` when the current component mounts, and also whenever we navigate to a URL.
必须在组件初始化期间调用 `afterNavigate`。只要组件已安装,它就会保持活动状态。
¥`afterNavigate` must be called during a component initialization. It remains active as long as the component is mounted.
```dts
function afterNavigate(
callback: (
navigation: import('@sveltejs/kit').AfterNavigate
) => void
): void;
```
## beforeNavigate
在我们导航到 URL 之前触发的导航拦截器,无论是通过单击链接、调用 `goto(...)` 还是使用浏览器的后退/前进控件。
¥A navigation interceptor that triggers before we navigate to a URL, whether by clicking a link, calling `goto(...)`, or using the browser back/forward controls.
调用 `cancel()` 将阻止导航完成。如果 `navigation.type === 'leave'` — 意味着用户正在离开应用(或关闭选项卡) — 调用 `cancel` 将触发原生浏览器卸载确认对话框。在这种情况下,导航可能会或可能不会被取消,具体取决于用户的响应。
¥Calling `cancel()` will prevent the navigation from completing. If `navigation.type === 'leave'` — meaning the user is navigating away from the app (or closing the tab) — calling `cancel` will trigger the native browser unload confirmation dialog. In this case, the navigation may or may not be cancelled depending on the user's response.
当导航不指向 SvelteKit 拥有的路由(因此由 SvelteKit 的客户端路由控制)时,`navigation.to.route.id` 将为 `null`。
¥When a navigation isn't to a SvelteKit-owned route (and therefore controlled by SvelteKit's client-side router), `navigation.to.route.id` will be `null`.
如果导航(如果没有取消)会导致文档卸载 — 换句话说,`'leave'` 导航和 `'link'` 导航,其中 `navigation.to.route === null` — `navigation.willUnload` 是 `true`。
¥If the navigation will (if not cancelled) cause the document to unload — in other words `'leave'` navigations and `'link'` navigations where `navigation.to.route === null` — `navigation.willUnload` is `true`.
必须在组件初始化期间调用 `beforeNavigate`。只要组件已安装,它就会保持活动状态。
¥`beforeNavigate` must be called during a component initialization. It remains active as long as the component is mounted.
```dts
function beforeNavigate(
callback: (
navigation: import('@sveltejs/kit').BeforeNavigate
) => void
): void;
```
## disableScrollHandling
如果在导航(例如,在 `onMount` 或 `afterNavigate` 或操作中)之后更新页面时调用,则会禁用 SvelteKit 的内置滚动处理。通常不鼓励这样做,因为它打破了用户的期望。
¥If called when the page is being updated following a navigation (in `onMount` or `afterNavigate` or an action, for example), this disables SvelteKit's built-in scroll handling.
This is generally discouraged, since it breaks user expectations.
```dts
function disableScrollHandling(): void;
```
## goto
允许你以编程方式导航到给定的路由,并提供诸如保持当前元素聚焦等选项。返回一个 Promise,当 SvelteKit 导航(或导航失败,在这种情况下 promise 被拒绝)到指定的 `url` 时解析。
¥Allows you to navigate programmatically to a given route, with options such as keeping the current element focused.
Returns a Promise that resolves when SvelteKit navigates (or fails to navigate, in which case the promise rejects) to the specified `url`.
对于外部 URL,请使用 `window.location = url`,而不是调用 `goto(url)`。
¥For external URLs, use `window.location = url` instead of calling `goto(url)`.
```dts
function goto(
url: string | URL,
opts?:
| {
replaceState?: boolean | undefined;
noScroll?: boolean | undefined;
keepFocus?: boolean | undefined;
invalidateAll?: boolean | undefined;
invalidate?:
| (string | URL | ((url: URL) => boolean))[]
| undefined;
state?: App.PageState | undefined;
}
| 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 中。
```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 { getRequestEvent, read } from '$app/server';
```
## getRequestEvent
自可用以来 2.20.0
¥Available since 2.20.0
返回当前 `RequestEvent`。可在服务器钩子、服务器 `load` 函数、操作和端点(以及它们调用的函数)中使用。
¥Returns the current `RequestEvent`. Can be used inside server hooks, server `load` functions, actions, and endpoints (and functions called by them).
在没有 [`AsyncLocalStorage`](https://nodejs.cn/api/async_context.html#class-asynclocalstorage) 的环境中,必须同步调用此函数(即不在 `await` 之后)。
¥In environments without [`AsyncLocalStorage`](https://nodejs.cn/api/async_context.html#class-asynclocalstorage), this must be called synchronously (i.e. not after an `await`).
```dts
function getRequestEvent(): RequestEvent<
Partial>,
string | null
>;
```
## 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)。
```js
// @noErrors
import { navigating, page, updated } from '$app/state';
```
## navigating
表示正在进行的导航的只读对象,具有 `from`、`to`、`type` 和(如果是 `type === 'popstate'`)`delta` 属性。当没有导航发生时或在服务器渲染期间,值为 `null`。
¥A read-only object representing an in-progress navigation, with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties.
Values are `null` when no navigation is occurring, or during server rendering.
```dts
const navigating:
| import('@sveltejs/kit').Navigation
| {
from: null;
to: null;
type: null;
willUnload: null;
delta: null;
complete: null;
};
```
## page
包含当前页面信息的只读反应对象,可用于多种用例:
¥A read-only reactive object with information about the current page, serving several use cases:
* 检索组件树中任何位置的所有页面/布局的组合 `data`(另请参阅 [加载数据](/docs/kit/load))
¥retrieving the combined `data` of all pages/layouts anywhere in your component tree (also see [loading data](/docs/kit/load))
* 检索组件树中任何位置的 `form` prop 的当前值(另请参阅 [表单操作](/docs/kit/form-actions))
¥retrieving the current value of the `form` prop anywhere in your component tree (also see [form actions](/docs/kit/form-actions))
* 检索通过 `goto`、`pushState` 或 `replaceState` 设置的页面状态(另请参阅 [goto](/docs/kit/$app-navigation#goto) 和 [浅路由](/docs/kit/shallow-routing))
¥retrieving the page state that was set through `goto`, `pushState` or `replaceState` (also see [goto](/docs/kit/$app-navigation#goto) and [shallow routing](/docs/kit/shallow-routing))
* 检索元数据,例如你所在的 URL、当前路由及其参数,以及是否存在错误
¥retrieving metadata such as the URL you're on, the current route and its parameters, and whether or not there was an error
```svelte
Currently at {page.url.pathname}
{#if page.error}
Problem detected
{:else}
All systems operational
{/if}
```
`page` 的更改仅通过 Runes 提供。(旧版反应性语法不会反映任何更改)
¥Changes to `page` are available exclusively with runes. (The legacy reactivity syntax will not reflect any changes)
```svelte
```
在服务器上,只能在渲染期间读取值(换句话说,不能在 `load` 函数中读取)。在浏览器中,可以随时读取值。
¥On the server, values can only be read during rendering (in other words *not* in e.g. `load` functions). In the browser, the values can be read at any time.
```dts
const page: import('@sveltejs/kit').Page;
```
## updated
最初为 `false` 的只读反应值。如果 [`version.pollInterval`](/docs/kit/configuration#version) 是非零值,SvelteKit 将轮询应用的新版本,并在检测到新版本时将 `current` 更新为 `true`。`updated.check()` 将强制立即检查,无论轮询如何。
¥A read-only reactive value that's initially `false`. If [`version.pollInterval`](/docs/kit/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update `current` to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling.
```dts
const updated: {
get current(): boolean;
check(): Promise;
};
```
# $app/stores
此模块包含 [`$app/state`]($app-state) 导出的基于存储的等效项。如果你使用的是 SvelteKit 2.12 或更高版本,请改用该模块。
¥This module contains store-based equivalents of the exports from [`$app/state`]($app-state). If you're using SvelteKit 2.12 or later, use that module instead.
```js
// @noErrors
import { getStores, navigating, page, updated } from '$app/stores';
```
## getStores
```dts
function getStores(): {
page: typeof page;
navigating: typeof navigating;
updated: typeof updated;
};
```
## navigating
改用 `$app/state` 中的 `navigating`(需要 Svelte 5、[查看文档了解更多信息](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))
¥Use `navigating` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))
可读存储。导航开始时,其值是具有 `from`、`to`、`type` 和(如果是 `type === 'popstate'`)`delta` 属性的 `Navigation` 对象。导航完成后,其值将恢复为 `null`。
¥A readable store.
When navigating starts, its value is a `Navigation` object with `from`, `to`, `type` and (if `type === 'popstate'`) `delta` properties.
When navigating finishes, its value reverts to `null`.
在服务器上,只能在组件初始化期间订阅此存储。在浏览器中,可以随时订阅它。
¥On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.
```dts
const navigating: import('svelte/store').Readable<
import('@sveltejs/kit').Navigation | null
>;
```
## page
改用 `$app/state` 中的 `page`(需要 Svelte 5、[查看文档了解更多信息](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))
¥Use `page` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))
值包含页面数据的可读存储。
¥A readable store whose value contains page data.
在服务器上,只能在组件初始化期间订阅此存储。在浏览器中,可以随时订阅它。
¥On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.
```dts
const page: import('svelte/store').Readable<
import('@sveltejs/kit').Page
>;
```
## updated
改用 `$app/state` 中的 `updated`(需要 Svelte 5、[查看文档了解更多信息](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))
¥Use `updated` from `$app/state` instead (requires Svelte 5, [see docs for more info](/docs/kit/migrating-to-sveltekit-2#SvelteKit-2.12:-$app-stores-deprecated))
初始值为 `false` 的可读存储。如果 [`version.pollInterval`](/docs/kit/configuration#version) 为非零值,SvelteKit 将轮询应用的新版本,并在检测到新版本时将存储值更新为 `true`。`updated.check()` 将强制立即检查,无论轮询如何。
¥A readable store whose initial value is `false`. If [`version.pollInterval`](/docs/kit/configuration#version) is a non-zero value, SvelteKit will poll for new versions of the app and update the store value to `true` when it detects one. `updated.check()` will force an immediate check, regardless of polling.
在服务器上,只能在组件初始化期间订阅此存储。在浏览器中,可以随时订阅它。
¥On the server, this store can only be subscribed to during component initialization. In the browser, it can be subscribed to at any time.
```dts
const updated: import('svelte/store').Readable & {
check(): Promise;
};
```
# $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` 中,此行为取决于你的适配器。
# $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] 你需要运行 `npm run dev` 才能让 SvelteKit 在 `jsconfig.json` 或 `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%`(例如 `
```