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

SvelteKit 提供了几个钩子 - 拦截和覆盖框架默认行为的方法。

¥SvelteKit provides several hooks — ways to intercept and override the framework’s default behaviour.

最基本的钩子是 handle,它存在于 src/hooks.server.js 中。它接收一个 event 对象和一个 resolve 函数,并返回一个 Response

¥The most elementary hook is handle, which lives in src/hooks.server.js. It receives an event object along with a resolve function, and returns a Response.

resolve 是奇迹发生的地方:SvelteKit 将传入的请求 URL 与应用的路由匹配,导入相关代码(+page.server.js+page.svelte 文件等),加载路由所需的数据并生成响应。

¥resolve is where the magic happens: SvelteKit matches the incoming request URL to a route of your app, imports the relevant code (+page.server.js and +page.svelte files and so on), loads the data needed by the route, and generates the response.

默认的 handle 钩子如下所示:

¥The default handle hook looks like this:

src/hooks.server
export async function handle({ event, resolve }) {
	return await resolve(event);
}

对于页面(与 API 路由 相反),你可以使用 transformPageChunk 修改生成的 HTML:

¥For pages (as opposed to API routes), you can modify the generated HTML with transformPageChunk:

src/hooks.server
export async function handle({ event, resolve }) {
	return await resolve(event, {
		transformPageChunk: ({ html }) => html.replace(
			'<body',
			'<body style="color: hotpink"'
		)
	});
}

你还可以创建全新的路由:

¥You can also create entirely new routes:

src/hooks.server
export async function handle({ event, resolve }) {
	if (event.url.pathname === '/ping') {
		return new Response('pong');
	}

	return await resolve(event, {
		transformPageChunk: ({ html }) => html.replace(
			'<body',
			'<body style="color: hotpink"'
		)
	});
}
上一页 下一页
1
2
<h1>hello world</h1>
<a href="/ping">ping</a>