Module Federation, a new feature of Webpack 5, enables us to reuse bundle files across various independent applications (application webpack builds).
Technical Aspects
This feature is essentially just a configuration that can be added to webpack’s config object because all the magic of the Module Federation can be configured in your webpack.config.js file.
webpack.config.js
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin"); const htmlConfig = { // ... }; module.exports = { entry: './src/index.js', output: { publicPath: 'http://localhost:5200/', path: path.resolve(__dirname, 'dist') }, module: { // ... }, plugins: [ new ModuleFederationPlugin({ library: { type: "var", name: "FormApp" }, name: "FormApp", filename: "remoteEntry.js", exposes: { "./Form": "./src/Form" }, remotes: { App: "App", }, shared: { "@material-ui/core": { eager: true, singleton: true, }, "react": { eager: true, singleton: true, }, "react-dom": { eager: true, singleton: true, }, }, }), new CleanWebpackPlugin(), new HtmlWebpackPlugin(htmlConfig) ] };
We may add the Module Federation Plugin to our list of plugins in webpack.config.js.
Since Application 1 exposes the Form component, this is actually Application 1’s webpack configuration. Application 2 would need to use the Module Federation Plugin in order to consume the Form component.
const HtmlWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin"); module.exports = { // .... plugins: [ new ModuleFederationPlugin({ // ... remotes: { RemoteForm: "FormApp", }, shared: ["react", "react-dom"], }), // .... ] };
Conclusion
We will be able to share components and other javascript modules easily and directly between applications thanks to Webpack 5.