logologo
指南
实践
配置
插件
案例
博客
生态
Module Federation Examples
Practical Module Federation
Zephyr Cloud
Nx
简体中文
English
指南
实践
配置
插件
案例
博客
Module Federation Examples
Practical Module Federation
Zephyr Cloud
Nx
简体中文
English
logologo

插件开发

插件系统

插件

重试插件
Edit this page on GitHub
Next Page重试插件

#插件系统

Module Federation 提供了一套轻量的运行时插件系统,用以实现自身的大多数功能,并允许用户进行扩展。

开发者编写的插件能够修改 Module Federation 的默认行为,并添加各类额外功能,包括但不限于:

  • 获取上下文信息
  • 注册生命周期钩子
  • 修改 Module Federation 配置
  • ...

#开发插件

插件提供类似 () => ModuleFederationRuntimePlugin 的函数。

#插件示例

custom-runtime-plugin.ts
import type { ModuleFederationRuntimePlugin } from '@module-federation/enhanced/runtime';

const runtimePlugin: () => ModuleFederationRuntimePlugin = function () {
  return {
    name: 'my-runtime-plugin',
    beforeInit(args) {
      console.log('beforeInit: ', args);
      return args;
    },
    beforeRequest(args) {
      console.log('beforeRequest: ', args);
      return args;
    },
    afterResolve(args) {
      console.log('afterResolve', args);
      return args;
    },
    onLoad(args) {
      console.log('onLoad: ', args);
      return args;
    },
    async loadShare(args) {
      console.log('loadShare:', args);
    },
    async beforeLoadShare(args) {
      console.log('beforeloadShare:', args);
      return args;
    },
  };
};
export default runtimePlugin;

注册插件(两种方式选择一种即可):

  • 构建配置中注册插件
rspack.config.ts
const path = require('path');
module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      // ...
      runtimePlugins: [path.resolve(__dirname, './custom-runtime-plugin.ts')],
    }),
  ],
};
  • 运行时注册插件
import { registerPlugins } from '@module-federation/enhanced/runtime'
import runtimePlugin from 'custom-runtime-plugin.ts';

registerPlugins([runtimePlugin()]);

#插件结构

函数形式的插件可以 接受选项对象 并 返回插件实例,并通过闭包机制管理内部状态。

其中各部分的作用分别为:

  • name 属性用于标注插件名称。
  • fn 各类钩子。

#命名规范

插件的命名规范如下:

  • 插件的函数通过 default 导出。
  • 插件的 name 采用 xxx-plugin 格式。

下面是一个例子:

import type { ModuleFederationRuntimePlugin } from '@module-federation/enhanced/runtime';
const pluginFooBar = (): ModuleFederationRuntimePlugin => ({
  name: 'xxx-plugin',
  //...
});

export default pluginFooBar;

#hooks

参考 Runtime Hooks