Module Federation is a new feature in Webpack5.
What it does: Enables modules from different projects to be made available remotely to other projects in a plugin called the ModuleFederationPlugin
ModuleFederationPlugin plug-in
ModuleFederation Module sharing as a whole is concatenated through the ModuleFederationPlugin.
Remote: provides the module sharing service. Host: obtains the shared module
Module Federation schematic
Remote configuration:
//webpack.config.js
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin')
module.exports = {
...
devServer: {
port: 8080
},
plugins: [
new ModuleFederationPlugin({
name:'remoteVar'.${expose} // the output module name must have a unique ID.
filename:'remoteEntry.js'.// Build the file name
exposes: {// Optional, which attributes are exported to be consumed when used as Remote;
'./NewsList':'./src/NewsList'
},
shared: ['react'.'react-dom'] // If no Host exists, use its own.}})]Copy the code
The Host configuration:
//webpack.config.js
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin')
module.exports = {
...
devServer: {
port: 8081
},
plugins: [
new ModuleFederationPlugin({
remotes: {// Optional, which Remote to consume as Host;
remote:'remoteVar@http://localhost:8080/remoteEntry.js'
hostRemote:'hostRemoteVar@http://localhost:8082/remoteEntry.js'
},
shared: ['react'.'react-dom']]}})Copy the code
Consume imported remote remote:
let RemoteNewList = await import('remote/NewsList');
let RemoteNewList = await import('hostRemote/Slides');
Copy the code
Host/Remote configuration:
//webpack.config.js
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin')
module.exports = {
...
devServer: {
port: 8082
},
plugins: [
new ModuleFederationPlugin({
name:'hostRemoteVar'.filename:'remoteEntry.js'.// Build the file name
remotes: {// Optional, which Remote to consume as Host;
remote:'remoteVar@http://localhost:8080/remoteEntry.js',},exposes: {// Optional, which attributes are exported to be consumed when used as Remote;
'./Slides':'./src/Slides'
},
shared: ['react'.'react-dom']]}})Copy the code
Consume imported remote remote:
let RemoteNewList = await import('remote/NewsList');
Copy the code
Learn more about Module Federation