You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在d.ts中重导出React及UI库类型以支持插件系统?

插件系统中React与UI库类型重导出及JSX提示实现方案

1. 重导出React类型

在@my-scope/plugin的类型定义文件中,先导入React类型模块,再将PluginContext的React字段定义为typeof React,即可完整继承React的所有类型:

import * as React from 'react';

export module "@my-scope/plugin" {
  export interface PluginContext {
    // 完整重导出React类型
    React: typeof React;
    // 后续补充其他字段
  }
}

2. 重导出UI库类型

假设UI组件库类型来自@my-scope/ui,先导入该库的类型,再将ui字段定义为typeof UI,实现UI组件类型的完整重导出:

import * as React from 'react';
import * as UI from '@my-scope/ui';

export module "@my-scope/plugin" {
  export interface PluginContext {
    React: typeof React;
    // 重导出UI库的所有组件类型
    ui: typeof UI;
    // 修正registerDialog的参数类型定义
    registerDialog(dialogName: string, factory: () => JSX.Element): void;
  }
}

3. 配置JSX语法自动提示

为让插件中的JSX语法获得类型提示,需在类型定义文件中声明全局JSX命名空间,并关联到React的JSX类型:

import * as React from 'react';
import * as UI from '@my-scope/ui';

// 声明全局JSX命名空间,让TypeScript识别插件中的JSX语法
declare global {
  namespace JSX {
    interface IntrinsicElements extends React.JSX.IntrinsicElements {}
    interface Element extends React.ReactElement<any, any> {}
    interface ElementClass extends React.Component<any, any> {}
    type ElementAttributes<T> = React.HTMLAttributes<T>;
  }
}

export module "@my-scope/plugin" {
  export interface PluginContext {
    React: typeof React;
    ui: typeof UI;
    registerDialog(dialogName: string, factory: () => JSX.Element): void;
  }
}

4. 插件端使用示例

插件无需直接导入React,通过上下文获取即可获得完整类型提示:

import * as my from '@my-scope/plugin';

export function start(ctx: my.PluginContext) {
    const { Dialog, Button } = ctx.ui;

    ctx.registerDialog('dialog1', () => {
      return <Dialog onCustomEvent={(e) => console.log(e)}>
        <Button onClick={() => console.log('clicked')}>OK</Button>
      </Dialog>;
    });
}

内容的提问来源于stack exchange,提问作者aztack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:06:27