5月30日 23:35

How does the shared configuration in Module Federation work? How to resolve version conflicts?

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:

javascript
new ModuleFederationPlugin({ shared: { react: { singleton: true }, 'react-dom': { singleton: true }, lodash: { singleton: false } } })

Key Configuration Options:

  1. singleton (Singleton Mode)

    • true: Ensures only one instance of the dependency exists throughout the application
    • false: Allows multiple versions to coexist
    • Use case: Libraries like React and Vue that require global singletons must be set to true
  2. requiredVersion (Version Requirement)

    javascript
    shared: { 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
  3. strictVersion (Strict Version)

    • true: Strictly matches version, throws error if not satisfied
    • false: Allows version mismatch (default)
  4. eager (Eager Loading)

    • true: Loads the dependency during initial load, doesn't use async loading
    • false: 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:

  1. Prioritize already loaded versions: If a dependency has been loaded, other applications will reuse that version
  2. Version negotiation: When multiple applications need different versions, select a version that meets all application requirements
  3. 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
标签:Module Federation