The shared configuration in Module Federation is used to manage dependencies shared between multiple applications, avoiding duplicate loading of the same version of libraries. Here's a detailed explanation:
Basic Configuration Syntax:
javascriptnew ModuleFederationPlugin({ shared: { react: { singleton: true }, 'react-dom': { singleton: true }, lodash: { singleton: false } } })
Key Configuration Options:
-
singleton (Singleton Mode)
true: Ensures only one instance of the dependency exists throughout the applicationfalse: Allows multiple versions to coexist- Use case: Libraries like React and Vue that require global singletons must be set to true
-
requiredVersion (Version Requirement)
javascriptshared: { react: { singleton: true, requiredVersion: '^17.0.0' } }- Specifies the required version range
- If the loaded version doesn't meet requirements, the local version will be loaded
-
strictVersion (Strict Version)
true: Strictly matches version, throws error if not satisfiedfalse: Allows version mismatch (default)
-
eager (Eager Loading)
true: Loads the dependency during initial load, doesn't use async loadingfalse: Loads on-demand asynchronously (default)- Use case: Some libraries need to be initialized when the application starts
Version Conflict Resolution Strategy:
Module Federation uses the following strategies to resolve version conflicts:
- Prioritize already loaded versions: If a dependency has been loaded, other applications will reuse that version
- Version negotiation: When multiple applications need different versions, select a version that meets all application requirements
- Fallback handling: If unable to meet all requirements, fall back to the local version
Practical Application Example:
javascript// Remote application new ModuleFederationPlugin({ name: 'remoteApp', filename: 'remoteEntry.js', exposes: { './Button': './src/Button' }, shared: { react: { singleton: true, requiredVersion: deps.react, eager: true }, 'react-dom': { singleton: true, requiredVersion: deps['react-dom'] } } }) // Host application new ModuleFederationPlugin({ name: 'hostApp', remotes: { remoteApp: 'remoteApp@http://localhost:3001/remoteEntry.js' }, shared: { react: { singleton: true, requiredVersion: deps.react }, 'react-dom': { singleton: true, requiredVersion: deps['react-dom'] } } })
Important Notes:
- When sharing dependencies, ensure all applications use the same version range
- For libraries with side effects, consider setting eager: true
- Use version information from package.json as requiredVersion