乐闻世界logo
搜索文章和话题

What is Module Federation and how does it work?

2月19日 17:41

Module Federation is a revolutionary feature introduced in Webpack 5 that allows dynamic loading and sharing of code modules at runtime. Its core principle is to generate independent build artifacts at build time and achieve on-demand loading and sharing of modules through JavaScript dynamic import mechanisms at runtime.

Key Concepts:

  1. Host: The application that consumes remote modules, responsible for loading remote entries
  2. Remote: The application that exposes modules for other applications to use
  3. Shared: Dependency libraries shared between multiple applications to avoid duplicate loading

Working Principle:

Module Federation uses Webpack's ContainerPlugin and ContainerReferencePlugin to implement this functionality. Remote applications generate an entry file (remoteEntry.js) during the build process, which contains mapping information for all exposed modules. Host applications specify the remote applications to load and their entry file addresses through the remotes configuration field.

Configuration Example:

javascript
// Remote application configuration new ModuleFederationPlugin({ name: 'remoteApp', filename: 'remoteEntry.js', exposes: { './Button': './src/Button' }, shared: ['react', 'react-dom'] }) // Host application configuration new ModuleFederationPlugin({ name: 'hostApp', remotes: { remoteApp: 'remoteApp@http://localhost:3001/remoteEntry.js' }, shared: ['react', 'react-dom'] })

Advantages:

  • Achieves true micro-frontend architecture with independent development and deployment for each team
  • Runtime dynamic loading without rebuilding the entire application
  • Dependency sharing reduces duplicate code and optimizes loading performance
  • Flexible version management allows independent upgrades of individual modules
标签:Module Federation