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

能否通过装饰器查找并调用函数?插件化架构实现疑问

需求目标

我要为某产品开发核心浏览器库,其中部分功能的函数实现需根据定制需求差异化处理(称其为插件函数)。我希望不在库代码中管理这些插件函数,而是在不同代码库中维护,仅在CI/CD阶段安装并打包进产物。

应用配置会指定选用的插件函数,例如客户1使用foo,客户2使用bar。核心库若能通过参数确定要调用的正确函数则更为理想。


已完成工作

运行时中,我不知如何不通过“显式”if语句调用实现。我认为可行方案是使用装饰器,通过配置中的唯一名称查找对应函数。

我先定义了所有插件需使用的装饰器:

function pluginFunc(name: string) {
  console.log(`plugin func '${name}'`);

  return function (
    target: any,
    propertyKey: string,
    descriptor: PropertyDescriptor
  ) {
    console.log({ name, target, propertyKey, descriptor });
  };
}

export { pluginFunc };

并编写了一个自定义插件:

import { pluginFunc } from "./pluginFunc";

@pluginFunc("foo")
function pluginOne() {
  console.log("hello from plugin 1");
}

export { pluginOne }

现在我想在简单的index.ts文件中测试该方案:

/* async */ function callPlugin(name: string) {
  // find function by decorator and name and call it
}

callPlugin('foo');

疑问

  • 能否通过装饰器pluginFunc及指定名称,查找并调用未在编译时导入的函数?
  • 若此方案不可行,仅通过函数名称调用未导入的函数是否可行?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 07:33:22