This chapter introduces how to build Module Federation output in Rslib.
Module federation has some typical usage scenarios, including:
Module Federation can help you:
First install the Module Federation Rsbuild Plugin.
npm add @module-federation/rsbuild-plugin -DThen register the plugin in the rslib.config.ts file:
import { pluginModuleFederation } from '@module-federation/rsbuild-plugin';
import { pluginReact } from '@rsbuild/plugin-react';
import { defineConfig } from '@rslib/core';
export default defineConfig({
lib: [
// ... other format
{
format: 'mf',
output: {
distPath: './dist/mf',
// for production, add online assetPrefix here
assetPrefix: 'http://localhost:3001/mf',
},
// for Storybook to dev
dev: {
assetPrefix: 'http://localhost:3001/mf',
},
plugins: [
pluginModuleFederation(
{
name: 'rslib_provider',
exposes: {
// add expose here
},
// can not add 'remote' here, because you may build 'esm' or 'cjs' assets in one build.
// if you want the Rslib package use remote module, please see below.
shared: {
react: {
singleton: true,
},
'react-dom': {
singleton: true,
},
},
},
{},
),
],
},
],
// for Storybook to dev
server: {
port: 3001,
},
output: {
target: 'web',
},
plugins: [pluginReact()],
});In this way, we have completed the integration of Rslib Module as a producer. After the construction is completed, we can see that the mf directory has been added to the product, and consumers can directly consume this package.
In the above example we added a new format: 'mf' , which will help you add an additional Module Federation product, while also configuring the format of cjs and esm , which does not conflict.
However, if you want this Rslib Module to consume other producers at the same time, do not use the build configuration remote parameter, because in other formats, this may cause errors, please refer to the example below using the Module Federation runtime.
Rslib support developing Module Federation Rslib project with a host application.
rslib mf-dev command of libraryAdding the dev command to the package.json file:
{
"scripts": {
"dev": "rslib mf-dev"
}
}Then run the dev command can start the Module Federation development mode,
enabling consumption by your host app, along
with Hot Module Replacement (HMR).
npm run devSet up the host app to consume the Rslib Module Federation library. Check out the @module-federation/rsbuild-plugin for more information.
import { pluginModuleFederation } from '@module-federation/rsbuild-plugin';
import { defineConfig } from '@rsbuild/core';
import { pluginReact } from '@rsbuild/plugin-react';
export default defineConfig({
plugins: [
pluginReact(),
pluginModuleFederation(
{
name: 'rsbuild_host',
remotes: {
rslib: 'rslib@http://localhost:3001/mf/mf-manifest.json',
},
shared: {
react: {
singleton: true,
},
'react-dom': {
singleton: true,
},
},
// Enable this when the output of Rslib is build under 'production' mode, while the host app is 'development'.
// Reference: https://rslib.rs/guide/advanced/module-federation#faqs
shareStrategy: 'loaded-first',
},
{},
),
],
});Then start the host app with rsbuild dev.
Rslib support developing Module Federation Rslib project with Storybook.
rslib mf-dev command of libraryAdding the dev command to the package.json file:
{
"scripts": {
"dev": "rslib mf-dev"
}
}Then run the dev command can start the Module Federation development mode, enabling consumption by Storybook, along with Hot Module Replacement (HMR).
npm run devFirst, set up Storybook with the Rslib project. You can refer to the Storybook chapter to learn how to do this. In this chapter, we will use React as the framework for our example.
Install the following Storybook addons to let Storybook work with Rslib Module Federation:
npm add storybook-addon-rslib @module-federation/storybook-addon -DThen set up the Storybook configuration file .storybook/main.ts, specify the stories and addons, and set the framework with corresponding framework integration.
import { dirname, join } from 'node:path';
import type { StorybookConfig } from 'storybook-react-rsbuild';
function getAbsolutePath(value: string): any {
return dirname(require.resolve(join(value, 'package.json')));
}
const config: StorybookConfig = {
stories: [
'../stories/**/*.mdx',
'../stories/**/*.stories.@(js|jsx|mjs|ts|tsx)',
],
framework: {
name: getAbsolutePath('storybook-react-rsbuild'),
options: {},
},
addons: [
{
name: getAbsolutePath('storybook-addon-rslib'),
options: {
rslib: {
include: ['**/stories/**'],
},
},
},
{
name: '@module-federation/storybook-addon/preset',
options: {
// add your rslib module manifest here for storybook dev
// we have set dev.assetPrefix and server.port to 3001 in rslib.config.ts above
remotes: {
'rslib-module':
// you can also add shared here for storybook app
// shared: {}
'rslib-module@http://localhost:3001/mf/mf-manifest.json',
},
},
},
],
};
export default config;Import components from remote module.
import React from 'react';
// Load your remote module here, Storybook will act as the host app.
import { Counter } from 'rslib-module';
const Component = () => <Counter />;
export default {
title: 'App Component',
component: Component,
};
export const Primary = {};tsconfig.json.{
"compilerOptions": {
// ...
"paths": {
"*": ["./@mf-types/*"]
}
},
"include": ["src/**/*", ".storybook/**/*", "stories/**/*"]
}There you go, start Storybook with npx storybook dev.
Because there are multiple formats in Rslib, if you configure the remote parameter to consume other modules during construction, it may not work properly in all formats. It is recommended to access through the Module Federation Runtime
First install the runtime dependencies
npm add @module-federation/enhanced -DThen consume other Module Federation modules at runtime, for example
import { init, loadRemote } from '@module-federation/enhanced/runtime';
import { Suspense, createElement, lazy } from 'react';
init({
name: 'rslib_provider',
remotes: [
{
name: 'mf_remote',
entry: 'http://localhost:3002/mf-manifest.json',
},
],
});
export const Counter: React.FC = () => {
return (
<div>
<Suspense fallback={<div>loading</div>}>
{createElement(
lazy(
() =>
loadRemote('mf_remote') as Promise<{
default: React.FC;
}>,
),
)}
</Suspense>
</div>
);
};This ensures that modules can be loaded as expected in multiple formats.
If the Rslib producer is built with build, this means that the process.env.NODE_ENV of the producer is production . If the consumer is started in dev mode at this time,
due to the shared loading strategy of Module Federation being version-first by default, there may be problems loading into different modes of react and react-dom (e.g. react in development mode, react-dom in production mode).
You can set up shareStrategy at the consumer to solve this problem, but make sure you fully understand this configuration
pluginModuleFederation({
// ...
shareStrategy: 'loaded-first',
}, {}),If you want Rslib producers' module federated outputs to generate the export of ES Modules, you can additionally configure as follows:
export default defineConfig({
lib: [
{
format: 'mf',
// ...
tools: {
rspack(config) {
config.experiments = {
outputModule: true,
};
},
},
},
],
});You can refer to the example projects in Rslib Module Federation Example.
mf-host: Rsbuild App Consumermf-react-component: Rslib Module, which is both a producer and a consumer, provides the module to the mf-host as a producer, and consumes the mf-remotemf-remote: Rsbuild App Producer