我想要创建一个反应应用程序,使用插件一样的基础设施。也就是说,在应用程序中有一些基本的功能总是可用的,但是它可以通过插件来增强,插件可以通过设置环境变量的配置文件来启用。
我已经实现了动态导入组件和Javascript函数的目标,但我在动态导入类型时遇到了问题,只有在启用插件时才应该使用这些类型。我创建了一个App示例,它显示了我采用的方法(也不确定这是否是最好的方法)。您可以在这里找到整个应用程序:我在Stackblitz上的应用
在App.tsx文件中,所有的内容都聚集在一起:
import * as React from 'react';
import CompA from './components/CompA';
function App() {
// const ENV_VARS = window.__RUNTIME_CONFIG__;
// let showPlugin1: boolean = ENV_VARS.ENABLED_PLUGINS.includes('PLUGIN_1');
let showPlugin1 = true;
let PluginB: any;
let PluginC: any;
let FuncA: any = undefined;
const [FuncVal, setFuncVal] = React.useState<string | undefined>();
let TypedFunction: any = undefined;
if (showPlugin1) {
PluginB = React.lazy(() => import('./components/plugins/CompB'));
PluginC = React.lazy(() => import('./exports/CompC'));
const loader = async () => {
({ FuncA } = await import('./components/plugins/Functions'));
setFuncVal(FuncA());
};
loader();
// import type {TypeA} from './components/plugins/Functions';
// TypedFunction = (testType: TypeA) => {
// return <div>Function Call with TypeA</div>
// }
}
return (
<React.Fragment>
<CompA />
<React.Suspense fallback={<div>Loading Plugins...</div>}>
{PluginB && <PluginB />}
{PluginC && <PluginC />}
{FuncVal && FuncVal}
{TypedFunction && TypedFunction()}
</React.Suspense>
</React.Fragment>
);
}
export default App;如您所见,我已经注释掉了试图根据变量设置从文件导入类型的部分。另外,我从设置文件中读取环境变量的部分也被注释掉了,因为这似乎不适用于Stackblitz。
任何帮助都将不胜感激。
发布于 2022-10-28 10:46:58
好吧,这个问题有点蠢。我通过将类型定义移动到.d.ts文件来解决这个问题,这样我就不必再导出或导入它们了。
因此,我的解决方案,有一个基于插件的结构,如上述工作,现在很好。我不是说这是最好的解决办法,但至少有效。
https://stackoverflow.com/questions/74222324
复制相似问题