0Pricing
Micro Frontends Architecture with Module Federation · 课时

单例模块与版本管理

了解如何确保模块只加载一个实例,并管理版本冲突。

单例模块与版本管理 是 CoddyKit 上的免费 Micro Frontends Architecture with Module Federation 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Micro Frontends Architecture with Module Federation 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Micro Frontends Architecture with Module Federation 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What are Singleton Modules?

In Micro Frontend architectures, a singleton module is a piece of code or a library that should only ever exist as a single instance across your entire application, even if multiple Micro Frontends try to load it.

Think of it as a unique resource that all parts of your system need to share consistently.

  • Ensures a single source of truth.
  • Prevents conflicting states or behaviors.

Why Singletons Matter for MFEs

Imagine multiple Micro Frontends (MFEs) all loading their own copy of a UI library like React, or a state management library like Redux.

Without singletons, you could end up with:

  • Multiple instances of React Context, breaking component communication.
  • Separate Redux stores, leading to inconsistent application state.
  • Increased bundle size due to duplicate code.

Singletons solve these issues by guaranteeing a unified dependency.

Implementing Singletons with MF

Module Federation makes it easy to declare shared modules as singletons using the singleton: true option in your Webpack configuration.

When this is set, Webpack ensures that only one version of the specified module is loaded and used by all federated applications (hosts and remotes) at runtime.

Code: Configuring a Singleton

Here's how you'd configure a shared module, like react, to be a singleton in your webpack.config.js:

const { ModuleFederationPlugin } = require('webpack').container;

module.exports = {
  // ... other Webpack config
  plugins: [
    new ModuleFederationPlugin({
      name: 'host_app',
      remotes: {},
      shared: {
        react: {
          singleton: true, // Only one React instance allowed
          requiredVersion: '^18.0.0',
        },
        'react-dom': {
          singleton: true, // Only one ReactDOM instance allowed
          requiredVersion: '^18.0.0',
        },
      },
    }),
  ],
};

Understanding Shared Module Versioning

Beyond ensuring a single *instance* (singleton), you also need to manage which *version* of a shared module gets loaded.

What if one MFE needs React v17 and another needs React v18? Module Federation has mechanisms to handle these version conflicts and ensure compatibility or gracefully fail.

`requiredVersion` for Specificity

The requiredVersion option in the shared configuration allows you to specify the semantic version (semver) range that your application expects for a shared module.

Webpack will try to find a compatible version among the host and remote applications. If a compatible version is found, it's used. If not, it might load a fallback or throw an error, depending on other settings.

Code: Specifying Required Versions

Here's how you might define a requiredVersion for a shared library:

const { ModuleFederationPlugin } = require('webpack').container;

module.exports = {
  // ...
  plugins: [
    new ModuleFederationPlugin({
      // ...
      shared: {
        lodash: {
          singleton: false,
          requiredVersion: '^4.17.21', // Any version compatible with 4.17.21
        },
        moment: {
          singleton: true,
          requiredVersion: '2.29.1', // Exactly version 2.29.1
        },
      },
    }),
  ],
};

`strictVersion: true` for Strictness

While requiredVersion guides version selection, strictVersion: true enforces it rigorously.

If strictVersion: true is enabled and a remote module requests a version that is incompatible with the host's requiredVersion (or the version already loaded), Module Federation will throw an error and prevent the application from loading. This prevents unexpected behavior from version mismatches.

Code: Enforcing Strict Versioning

Combining singleton, requiredVersion, and strictVersion for critical dependencies:

const { ModuleFederationPlugin } = require('webpack').container;

module.exports = {
  // ...
  plugins: [
    new ModuleFederationPlugin({
      // ...
      shared: {
        react: {
          singleton: true,
          requiredVersion: '^18.0.0',
          strictVersion: true, // Fail if versions are incompatible
        },
        // ... other shared modules
      },
    }),
  ],
};

Best Practices for Shared Dependencies

To effectively manage singleton modules and versioning:

  • Use Semantic Versioning (SemVer): Adhere to major.minor.patch for all shared modules.
  • Communicate: Ensure teams are aware of shared module updates and version requirements.
  • Test Compatibility: Regularly test your federated applications to ensure shared modules work across all remotes and hosts.
  • Be Strategic: Not all shared modules need to be singletons or have strict versioning. Apply these settings thoughtfully based on the module's criticality.

Quick Check: Singleton & Versioning

When configuring shared modules in Module Federation, what are the primary benefits of using singleton: true and strictVersion: true?

Recap & Next Steps

You've now learned about singleton modules and versioning in Module Federation!

  • Singleton modules ensure only one instance of a shared dependency exists across your federated application, crucial for stateful libraries.
  • The requiredVersion and strictVersion options help manage compatibility and prevent issues arising from conflicting module versions.

These techniques are vital for building robust and predictable Micro Frontend applications.

常见问题解答

「单例模块与版本管理」课时是免费的吗?

是的 — 「单例模块与版本管理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Micro Frontends Architecture with Module Federation 课程的其余内容,请升级到 CoddyKit PRO。 Micro Frontends Architecture with Module Federation 课程共包含 4 节课。

「单例模块与版本管理」这节课中我会学到什么?

了解如何确保模块只加载一个实例,并管理版本冲突。 你通过在浏览器中直接运行的动手代码来练习 Micro Frontends Architecture with Module Federation,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Micro Frontends Architecture with Module Federation 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Micro Frontends Architecture with Module Federation 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「单例模块与版本管理」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Micro Frontends Architecture with Module Federation 课中编写并运行代码吗?

能。每节 Micro Frontends Architecture with Module Federation 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用共享依赖
  2. 单例模块与版本管理
  3. 动态加载模块
  4. 在远程应用之间共享状态与工具
← 返回 Micro Frontends Architecture with Module Federation