` 不再是必需的。
¥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(
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
): 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): 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): Response;
```
## 操作(Action)
¥Action
`+page.server.js` 中 `export const actions = {...}` 一部分的表单操作方法的形状。有关更多信息,请参阅 [表单操作](/docs/kit/form-actions)。
¥Shape of a form action method that is part of `export const actions = {...}` in `+page.server.js`.
See [form actions](/docs/kit/form-actions) for more information.
```dts
type Action<
Params extends
AppLayoutParams<'/'> = AppLayoutParams<'/'>,
OutputData extends Record
| void = Record<
string,
any
> | void,
RouteId extends AppRouteId | null = AppRouteId | null
> = (
event: RequestEvent
) => MaybePromise;
```
## ActionFailure
```dts
interface ActionFailure
{/*…*/}
```
```dts
status: number;
```
```dts
[uniqueSymbol]: true;
```
## ActionResult
通过 fetch 调用表单操作时,响应将是这些形状之一。
¥When calling a form action via fetch, the response will be one of these shapes.
```svelte