Webpack5 has an exciting new feature: module federation. See what it can do
Application scenarios
Cross-project dependencies can be resolved by assuming that there are currently two projects app1 and App2, and App1 wants to use one of the components in the App2 project such as SRC/Components/button.js. Components could be split into a common component library and introduced separately in App1 and App2, but maintaining and updating the component library would be tedious, and extracting each module would be overly abstract, but module federation would solve this problem painlessly.
use
There is no introduction to webpack5 documentation, but we recommend a sample repository, module-federation-examples, that contains complete use cases for multiple scenarios.
Simple to use
App1 relies on app2 modules:
// app1/webpack.config.js
new ModuleFederationPlugin({
name: "app1".library: { type: "var".name: "app1" },
remotes: {
app2: "app2"
},
shared: ["react"."react-dom"]}),Copy the code
// app2/webpack.config.js
new ModuleFederationPlugin({
name: "app2".library: { type: "var".name: "app2" },
filename: "remoteEntry.js".exposes: {
Button: "./src/Button",},shared: ["react"."react-dom"]}),Copy the code
Describes the configurations used
- The name of module
- {type: “commonjs-module”} {type: “commonjs-module”}, which can be used to specify the usage of modules
- The name of the module remotes depends on
- Filename app1 uses the entry of the app2 module. App1 needs to load remoteentry. js first
- An expose app2 module, which can have multiple
- When shared App2 packages exposed modules, it will not package shared, and app2’s Button will use app1’s React
How are cross-application dependencies implemented
To do this, App2 will pack up a small remoteentry. js file that contains all of app2’s modules. App1 will need to import this remoteentry. js file first. App1 relies on app2/Button when it is running. In this case, use remoteentry. js to find the corresponding address of button.js and load and execute it.
As you can see, dependencies are runtime, and modules are loaded as needed from the information recorded in remoteentry.js. Remoteentry. js is small and should not be cached to ensure that App1 gets the latest app2 code. After app2 is updated, App1 can use the new version of app2 code without any changes.