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:
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
:
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:
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"'
)
});
}
<h1>hello world</h1>
<a href="/ping">ping</a>