插件
¥Plugins
使用插件扩展 Nitro 的运行时行为。
Nitro 插件将在服务器启动时执行一次,以扩展 Nitro 的运行时行为。它们接收 nitroApp
上下文,可用于挂载到 Nitro 生命周期事件。
¥Nitro plugins will be executed once during server startup in order to allow extending Nitro's runtime behavior.
They receive nitroApp
context, which can be used to hook into Nitro lifecycle events.
插件从 plugins/
目录自动注册,并在首次 Nitro 初始化时同步运行(按文件名顺序)。
¥Plugins are auto-registered from plugins/
directory and run synchronously (by order of file name) on the first Nitro initialization.
示例:
¥Example:
export default defineNitroPlugin((nitroApp) => {
console.log('Nitro plugin', nitroApp)
})
如果你的插件位于其他目录,则可以使用 plugins
选项:
¥If you have plugins in another directory, you can use the plugins
option:
export default defineNitroConfig({
plugins: ['my-plugins/hello.ts']
})
Nitro 运行时钩子
¥Nitro runtime hooks
你可以使用 Nitro hooks 扩展 Nitro 的默认运行时行为,方法是将自定义(异步或同步)函数注册到插件中的生命周期事件。
¥You can use Nitro hooks to extend the default runtime behaviour of Nitro by registering custom (async or sync) functions to the lifecycle events within plugins.
示例:
¥Example:
export default defineNitroPlugin((nitro) => {
nitro.hooks.hook("close", async () => {
// Will run when nitro is being closed
});
})
可用钩子
¥Available hooks
请参阅 源代码 了解所有可用的运行时钩子列表。
¥See the source code for list of all available runtime hooks.
"close", () => {}
"error", (error, { event? }) => {}
"render:response", (response, { event }) => {}
"request", (event) => {}
"beforeResponse", (event, { body }) => {}
"afterResponse", (event, { body }) => {}
示例
¥Examples
捕获错误
¥Capturing errors
你可以使用插件捕获所有应用错误。
¥You can use plugins to capture all application errors.
export default defineNitroPlugin((nitro) => {
nitro.hooks.hook("error", async (error, { event }) => {
console.error(`${event.path} Application error:`, error)
});
})
优雅关闭
¥Graceful shutdown
你可以使用插件注册一个在 Nitro 关闭时解析的钩子。
¥You can use plugins to register a hook that resolves when Nitro is closed.
export default defineNitroPlugin((nitro) => {
nitro.hooks.hookOnce("close", async () => {
// Will run when nitro is closed
console.log("Closing nitro server...")
await new Promise((resolve) => setTimeout(resolve, 500));
console.log("Task is done!");
});
})
请求和响应生命周期
¥Request and response lifecycle
你可以使用插件注册一个可以在请求生命周期中运行的钩子:
¥You can use plugins to register a hook that can run on request lifecycle:
export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook("request", (event) => {
console.log("on request", event.path);
});
nitroApp.hooks.hook("beforeResponse", (event, { body }) => {
console.log("on response", event.path, { body });
});
nitroApp.hooks.hook("afterResponse", (event, { body }) => {
console.log("on after response", event.path, { body });
});
});
渲染器响应
¥Renderer response
你可以使用插件注册一个修改 renderer
响应的钩子。
¥You can use plugins to register a hook that modifies the renderer
response.
export default defineNitroPlugin((nitro) => {
nitro.hooks.hook('render:response', (response, { event }) => {
// Inspect or Modify the renderer response here
console.log(response)
})
})