文档中心

探索 DWeb 框架的无限可能,构建下一代高性能 Web 应用

插件系统

DWeb 框架提供了灵活的插件系统,允许你扩展框架功能。

什么是插件

插件是一个对象,包含名称和初始化函数。插件可以:

  • 扩展框架功能
  • 添加全局中间件
  • 修改应用配置
  • 注册生命周期钩子
  • 注入 HTML 内容
  • 处理 API 请求

创建插件

创建一个自定义插件:

Code
import type { Plugin } from '@dreamer/dweb';

const myPlugin: Plugin = {
  name: 'my-plugin',
  setup(app) {
    // 插件初始化
    console.log('Plugin initialized');
  },
};

使用插件

在应用中使用插件:

Code
import { createApp } from '@dreamer/dweb';
import { tailwind, seo } from '@dreamer/dweb';

const app = createApp();

// 注册插件
app.plugin(tailwind({ version: 'v4' }));
app.plugin(seo({ title: 'My App' }));

export default app;

插件生命周期

插件支持多个生命周期钩子:

Code
import type { Plugin } from '@dreamer/dweb';

const myPlugin: Plugin = {
  name: 'my-plugin',
  
  // 应用初始化时执行
  onInit: async (app) => {
    console.log('插件初始化');
  },
  
  // 每个请求前执行
  onRequest: async (req, res) => {
    console.log('请求:', req.url);
  },
  
  // 每个响应后执行
  onResponse: async (req, res, html) => {
    // 可以修改 HTML 内容
    return html.replace('</body>', '<script>console.log("插件注入")</script></body>');
  },
  
  // 发生错误时执行
  onError: async (error, req, res) => {
    console.error('错误:', error);
  },
  
  // 构建时执行
  onBuild: async (config) => {
    console.log('构建配置:', config);
  },
};

生命周期钩子说明

  • onInit - 应用初始化时执行,用于设置插件初始状态
  • onRequest - 每个请求前执行,可以拦截请求或处理 API 路由
  • onResponse - 每个响应后执行,可以修改响应内容或注入 HTML
  • onError - 发生错误时执行,用于错误处理和日志记录
  • onBuild - 构建时执行,用于构建时的处理逻辑

插件配置

插件可以接受配置选项:

Code
// 插件可以接受配置
const myPlugin = (options: { apiKey: string }) => ({
  name: 'my-plugin',
  onInit: async (app) => {
    console.log('API Key:', options.apiKey);
  },
});

// 使用插件
app.plugin(myPlugin({ apiKey: 'your-api-key' }));

API 参考

插件接口

Code
interface Plugin {
  name: string;
  onInit?: (app: AppLike) => Promise<void> | void;
  onRequest?: (req: Request, res: Response) => Promise<void> | void;
  onResponse?: (req: Request, res: Response, html: string) => Promise<string> | string;
  onError?: (error: Error, req: Request, res: Response) => Promise<void> | void;
  onBuild?: (config: AppConfig) => Promise<void> | void;
}

使用插件

Code
// 在 Application 上使用
app.plugin(plugin);

// 在配置文件中使用
export default {
  plugins: [
    tailwind({ version: 'v4' }),
    seo({ title: 'My App' }),
  ],
};

内置插件

框架提供了多个内置插件:

相关文档