Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

预渲染意味着在构建时为页面生成一次 HTML,而不是为每个请求动态生成 HTML。

¥Prerendering means generating HTML for a page once, at build time, rather than dynamically for each request.

优点是提供静态数据非常便宜且性能高,使你可以轻松地为大量用户提供服务,而不必担心缓存控制标头(这很容易出错)。

¥The advantage is that serving static data is extremely cheap and performant, allowing you to easily serve large numbers of users without worrying about cache-control headers (which are easy to get wrong).

代价是构建过程需要更长的时间,并且只能通过构建和部署新版本的应用来更新预渲染的内容。

¥The tradeoff is that the build process takes longer, and prerendered content can only be updated by building and deploying a new version of the application.

要预渲染页面,请将 prerender 设置为 true

¥To prerender a page, set prerender to true:

src/routes/+page.server
export const prerender = true;

在本教程中,这不会产生任何可观察到的效果,因为应用在 dev 模式下运行。

¥Here in the tutorial, this won’t have any observable effect, since the application is running in dev mode.

但并非所有导航都会导致错误,例如,如果下一页的 JavaScript 已加载。基本规则如下:为了使内容可预渲染,任何两个直接点击它的用户都必须从服务器获取相同的内容,并且页面不得包含表单操作。具有动态路由参数的页面可以预渲染,只要它们在 prerender.entries 配置中指定或可以通过跟踪 prerender.entries 中的页面的链接到达即可。

¥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 form actions. Pages with dynamic route parameters can be prerendered as long as they are specified in the prerender.entries configuration or can be reached by following links from pages that are in prerender.entries.

在根 +layout.server.js 中将 prerender 设置为 true 可有效地将 SvelteKit 变成静态站点生成器 (SSG)。

¥[!NOTE] Setting prerender to true inside your root +layout.server.js effectively turns SvelteKit into a static site generator (SSG).

上一页 下一页
1
2
<h1>Prerendering</h1>