插件

¥Plugins

H3 插件允许你使用可重用逻辑扩展 H3 应用实例。

¥H3 plugins allow you to extend an H3 app instance with reusable logic.

注册插件

¥Register Plugins

插件可以在创建新的 H3 实例 时注册,也可以使用 H3.register 注册。

¥Plugins can be registered either when creating a new H3 instance or by using H3.register.

import { H3 } from "h3";
import { logger } from "./logger.mjs";

// Using instance config
const app = new H3({
  plugins: [logger()],
});

// Or register later
app.register(logger());

// ... rest of the code..
app.get("/**", () => "Hello, World!");
插件始终会立即注册。因此,它们的使用顺序可能很重要,具体取决于插件的功能。¥!NOTE Plugins are always registered immediately. Therefore, the order in which they are used might be important depending on the plugin's functionality.

创建插件

¥Creating Plugins

H3 插件只是一些函数,它们接受 H3 实例 作为第一个参数,并立即应用逻辑来扩展它。

¥H3 plugins are simply functions that accept an H3 instance as the first argument and immediately apply logic to extend it.

app.register((app) => {
  app.use(...)
})

为方便起见,H3 提供了一个内置的 definePlugin 实用程序,它可以创建一个带有可选插件特定选项的类型化工厂函数。

¥For convenience, H3 provides a built-in definePlugin utility, which creates a typed factory function with optional plugin-specific options.

import { definePlugin } from "h3";

const logger = definePlugin((h3, _options) => {
  if (h3.config.debug) {
    h3.use((req) => {
      console.log(`[${req.method}] ${req.url}`);
    });
  }
});