PluginManager
用于管理插件。
1class PluginManager {
2 add<T = any>(plugin: typeof Plugin, opts?: PluginOptions<T>): Promise<void>
3
4 get<T extends typeof Plugin>(PluginClass: T): InstanceType<T>;
5 get<T extends {}>(name: string): T;
6}
实例方法
pluginManager.add()
将插件添加到应用中。
1class PluginManager {
2 add<T = any>(plugin: typeof Plugin, opts?: PluginOptions<T>): Promise<void>
3}
第一个参数是插件类,第二个则是实例化时传递的参数。前面已经讲过会在添加插件后,立即调用 afterAdd
钩子函数,所以返回的是 Promise<void>
。
对于远程组件而言,会自动传递一个 name
参数。
1class MyPluginA extends Plugin {
2 async load() {
3 console.log('options', this.options)
4 console.log('app', this.app);
5 console.log('router', this.app.router, this.router);
6 }
7}
8
9class MyPluginB extends Plugin {
10 // 需要在 afterAdd 执行添加的方法
11 async afterAdd() {
12 // 通过 `app.pluginManager.add()` 添加插件时,第一个参数是插件类,第二个参数是实例化时传递的参数
13 this.app.pluginManager.add(MyPluginA, { name: 'MyPluginA', hello: 'world' })
14 }
15}
16
17const app = new Application({
18 plugins: [MyPluginB],
19});
pluginManager.get()
获取插件实例。
1class PluginManager {
2 get<T extends typeof Plugin>(PluginClass: T): InstanceType<T>;
3 get<T extends {}>(name: string): T;
4}
可以通过 Class 获取插件示例,如果在插件注册的时候有 name,也可以通过字符串的 name 获取。
如果是远程插件,会自动传入 name,值为 package 的 name。
1import MyPluginA from 'xxx';
2
3class MyPluginB extends Plugin {
4 async load() {
5 // 方式1:通过 Class 获取
6 const myPluginA = this.app.pluginManager.get(MyPluginA);
7
8 // 方式2:通过 name 获取(添加的时候要传递 name 参数)
9 const myPluginA = this.app.pluginManager.get('MyPluginA');
10 }
11}
Hooks
获取插件实例,等同于 pluginManager.get()
。
usePlugin()
1function usePlugin<T extends typeof Plugin>(plugin: T): InstanceType<T>;
2function usePlugin<T extends {}>(name: string): T;
可以通过 Class 获取插件示例,如果在插件注册的时候有 name,也可以通过字符串的 name 获取。
1import { usePlugin } from '@tachybase/client';
2
3const Demo = () => {
4 // 通过 Class 获取
5 const myPlugin = usePlugin(MyPlugin);
6
7 // 通过 name 获取(添加的时候要传递 name 参数)
8 const myPlugin = usePlugin('MyPlugin');
9
10 return <div></div>
11}