Module Federation
This chapter introduces how to build Module Federation output in Rslib.
Usage scenarios
Module federation has some typical usage scenarios, including:
- Allows independent applications (called "Micro-Frontend" in the Micro-Frontend architecture) to share modules without having to recompile the entire application.
- Different teams work on different parts of the same application without having to recompile the entire application.
- Dynamic code loading and sharing between applications at runtime.
Module Federation can help you:
- Reduce code duplication
- Improve code maintainability
- Reduce the overall size of the application
- Improve application performance
Quick Start
First install the Module Federation Rsbuild Plugin.
npm add @module-federation/rsbuild-plugin -D
Then add the plugin to the rslib.config.ts
file:
rslib.config.ts
1import { pluginModuleFederation } from '@module-federation/rsbuild-plugin';
2import { pluginReact } from '@rsbuild/plugin-react';
3import { defineConfig } from '@rslib/core';
4
5export default defineConfig({
6 lib: [
7 // ... other format
8 {
9 format: 'mf',
10 output: {
11 distPath: {
12 root: './dist/mf',
13 },
14 // for production, add online assetPrefix here
15 assetPrefix: 'http://localhost:3001/mf',
16 },
17 // for Storybook to dev
18 dev: {
19 assetPrefix: 'http://localhost:3001/mf',
20 },
21 // for Storybook to dev
22 server: {
23 port: 3001,
24 },
25 plugins: [
26 pluginModuleFederation({
27 name: 'rslib_provider',
28 exposes: {
29 // add expose here
30 },
31 // can not add 'remote' here, because you may build 'esm' or 'cjs' assets in one build.
32 // if you want the Rslib package use remote module, please see below.
33 shared: {
34 react: {
35 singleton: true,
36 },
37 'react-dom': {
38 singleton: true,
39 },
40 },
41 }),
42 ],
43 },
44 ],
45 output: {
46 target: 'web',
47 },
48 plugins: [pluginReact()],
49});
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
Develop MF remote module
Use Host App
Rslib support developing Module Federation Rslib project with a host application.
1. Start MF dev
of library
Adding the dev
command to the package.json
file:
package.json
{
"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).
2. Start Host App
Set up the host app to consume the Rslib Module Federation library. Check out the @module-federation/rsbuild-plugin
for more information.
rsbuild.config.ts
1import { pluginModuleFederation } from '@module-federation/rsbuild-plugin';
2import { defineConfig } from '@rsbuild/core';
3import { pluginReact } from '@rsbuild/plugin-react';
4
5export default defineConfig({
6 plugins: [
7 pluginReact(),
8 pluginModuleFederation({
9 name: 'rsbuild_host',
10 remotes: {
11 rslib: 'rslib@http://localhost:3001/mf/mf-manifest.json',
12 },
13 shared: {
14 react: {
15 singleton: true,
16 },
17 'react-dom': {
18 singleton: true,
19 },
20 },
21 // Enable this when the output of Rslib is build under 'production' mode, while the host app is 'development'.
22 // Reference: https://lib.rsbuild.dev/guide/advanced/module-federation#faqs
23 shareStrategy: 'loaded-first',
24 }),
25 ],
26});
Then start the host app with rsbuild dev
.
Use Storybook
Rslib support developing Module Federation Rslib project with Storybook.
1. Start MF dev
of library
Adding the dev
command to the package.json
file:
package.json
{
"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).
2. Set up Storybook configuration
First, 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 -D
-
Then set up the Storybook configuration file .storybook/main.ts
, specify the stories and addons, and set the framework with corresponding framework integration.
.storybook/main.ts
1import { dirname, join } from 'node:path';
2import type { StorybookConfig } from 'storybook-react-rsbuild';
3
4function getAbsolutePath(value: string): any {
5 return dirname(require.resolve(join(value, 'package.json')));
6}
7
8const config: StorybookConfig = {
9 stories: [
10 '../stories/**/*.mdx',
11 '../stories/**/*.stories.@(js|jsx|mjs|ts|tsx)',
12 ],
13 framework: {
14 name: getAbsolutePath('storybook-react-rsbuild'),
15 options: {},
16 },
17 addons: [
18 {
19 name: getAbsolutePath('storybook-addon-rslib'),
20 options: {
21 rslib: {
22 include: ['**/stories/**'],
23 },
24 },
25 },
26 {
27 name: '@module-federation/storybook-addon/preset',
28 options: {
29 // add your rslib module manifest here for storybook dev
30 // we have set dev.assetPrefix and server.port to 3001 in rslib.config.ts above
31 remotes: {
32 'rslib-module':
33 // you can also add shared here for storybook app
34 // shared: {}
35 'rslib-module@http://localhost:3001/mf/mf-manifest.json',
36 },
37 },
38 },
39 ],
40};
41
42export default config;
3. Writing stories with remote module
Import components from remote module.
stories/index.stories.tsx
1import React from 'react';
2// Load your remote module here, Storybook will act as the host app.
3import { Counter } from 'rslib-module';
4
5const Component = () => <Counter />;
6
7export default {
8 title: 'App Component',
9 component: Component,
10};
11
12export const Primary = {};
4. Add Module Federation types and stories into tsconfig.json
.
tsconfig.json
{
"compilerOptions": {
// ...
"paths": {
"*": ["./@mf-types/*"]
}
},
"include": ["src/**/*", ".storybook/**/*", "stories/**/*"]
}
5. Start Storybook app
There you go, start Storybook with npx storybook dev
.
Consume other Module Federation modules
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 -D
Then 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.
FAQs
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 policy 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',
}),
Examples
Rslib Module Federation Example
mf-host
: Rsbuild App Consumer
mf-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-remote
mf-remote
: Rsbuild App Producer
Rslib Module Federation Storybook Example