Plugin System

Module Federation provides a lightweight runtime plugin system for implementing most of its features and allowing users to extend functionalities.

Plugins developed by developers can modify the default behavior of Module Federation and add various additional features, including but not limited to:

  • Obtaining context information
  • Registering lifecycle hooks
  • Modifying Module Federation configurations
  • ...

Developing Plugins

Plugins are provided in the form of a function similar to () => ModuleFederationRuntimePlugin.

Plugin Example

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;

Registering plugins (either method is acceptable):

  • Build-time registration of plugins
rspack.config.ts
const path = require('path');
module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      // ...
      runtimePlugins: [path.resolve(__dirname, './custom-runtime-plugin.ts')],
    }),
  ],
};
  • Runtime registration of plugins
import { registerPlugins } from '@module-federation/enhanced/runtime'
import runtimePlugin from 'custom-runtime-plugin.ts';

registerPlugins([runtimePlugin()]);

Plugin Structure

Function-based plugins can accept an options object and return a plugin instance, managing internal state through closure mechanisms.

The roles of each part are as follows:

  • The name property is used to label the plugin name.
  • fn Various hooks.

Naming Conventions

The naming conventions for plugins are as follows:

  • The plugin function is named xxx-plugin and is exported with a name.
  • The name of the plugin follows the xxx-plugin format.

Here is an example:

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

export default pluginFooBar;

Hooks

Refer to Runtime Hooks