0Pricing
Micro Frontends Architecture with Module Federation · 课时

自定义通信方案

针对特定的微前端需求,设计并实现定制化通信机制。

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

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

Beyond Standard Communication

In Micro Frontend architectures, communication between different parts is crucial. We've explored event buses and shared state management.

However, sometimes your specific needs might call for more tailored approaches. This lesson dives into designing and implementing custom communication solutions.

Why Custom Solutions?

Why would you choose a custom solution over an established pattern?

  • Specific Interaction: When a very particular, direct interaction is needed.
  • Performance: To optimize for very high-frequency or low-latency communication.
  • Minimal Overhead: For simple, ad-hoc needs without bringing in heavy libraries.
  • Tight Coupling (Rare): In scenarios where two MFEs are intentionally very close and share a parent context.

Direct Callback Passing

One custom approach involves passing functions (callbacks) directly from a host application to a remote application as props or arguments. This is suitable when a host component directly renders a remote component and needs to react to its actions.

Module Federation allows you to share functions just like components or data.

Example: Passing a Callback

Imagine a host passing a 'notify' function to a remote, which then calls it. This is a simplified JavaScript representation:

function hostApp() {
  function handleNotification(message) {
    console.log(`Host received: ${message}`);
  }

  // In a real MFE, remote would be loaded
  // and `onNotify` passed as a prop.
  // For demo, we'll simulate the call.
  console.log("Host ready to receive.");
  remoteApp(handleNotification);
}

function remoteApp(onNotify) {
  console.log("Remote app started.");
  setTimeout(() => {
    onNotify("Data processed successfully!");
  }, 1000);
}

hostApp();

Browser's postMessage API

The postMessage API is a powerful browser feature for secure cross-origin communication between windows, iframes, and Web Workers.

It's ideal for sending messages between a host and an embedded MFE (e.g., in an iframe) where direct JavaScript access is restricted due to security policies.

Example: postMessage (Conceptual)

This is how a host and remote (e.g., in an iframe) would conceptually use postMessage to communicate. Note: This requires a browser environment to run fully.

// Host (parent window):
// const iframe = document.getElementById('remote-mfe');
// iframe.contentWindow.postMessage('Hello from Host!', 'http://remote.com');
// window.addEventListener('message', (event) => {
//   if (event.origin === 'http://remote.com') {
//     console.log('Host received:', event.data);
//   }
// });

// Remote (inside iframe):
// window.addEventListener('message', (event) => {
//   if (event.origin === 'http://host.com') {
//     console.log('Remote received:', event.data);
//     event.source.postMessage('Hello from Remote!', event.origin);
//   }
// });

// This snippet simulates the message flow:
function simulatePostMessage() {
  console.log("Simulating postMessage...");
  const hostMessage = "Hello from Host!";
  const remoteMessage = "Hello from Remote!";

  // Host sends to Remote
  console.log(`Host sends: "${hostMessage}"`);

  // Remote receives and replies
  console.log(`Remote receives: "${hostMessage}"`);
  console.log(`Remote sends: "${remoteMessage}"`);

  // Host receives reply
  console.log(`Host receives: "${remoteMessage}"`);
}

simulatePostMessage();

Shared Global Registry/Service

For specific, limited global data or services, you can create a custom JavaScript object or class and expose it via Module Federation's shared scope.

This acts like a lightweight, custom singleton that all federated applications can access and interact with, without full state management.

Example: Custom Shared Registry

Here's a simple custom registry object that could be shared. Each MFE could import and use mySharedRegistry.

// mySharedRegistry.js (exposed via Module Federation)
const mySharedRegistry = {
  _data: {},
  set: function(key, value) {
    this._data[key] = value;
    console.log(`Registry updated: ${key} = ${value}`);
  },
  get: function(key) {
    return this._data[key];
  },
  getAll: function() {
    return { ...this._data };
  }
};

// Simulate usage in different MFEs
console.log("--- MFE A ---");
mySharedRegistry.set("userTheme", "dark");

console.log("--- MFE B ---");
console.log(`Current user theme: ${mySharedRegistry.get("userTheme")}`);
mySharedRegistry.set("appVersion", "1.0.1");

console.log("--- MFE A (again) ---");
console.log(`Current app version: ${mySharedRegistry.get("appVersion")}`);

Considerations & Trade-offs

While custom solutions offer flexibility, they come with trade-offs:

  • Increased Coupling: Can make MFEs less independent.
  • Complexity: Harder to maintain and debug compared to standard patterns.
  • Scalability: May not scale well if communication needs grow.
  • Security: `postMessage` needs careful origin validation.

Always weigh the benefits against these potential drawbacks.

Custom Communication Check

You're implementing a Micro Frontend architecture. One MFE is embedded in an iframe on a different domain. You need to send simple messages between the host and the iframe securely.

Recap: Custom Solutions

We explored custom communication solutions for Micro Frontends, going beyond event buses and shared state.

  • Direct Callbacks: For tightly coupled components.
  • postMessage API: For secure cross-origin communication, especially with iframes.
  • Shared Registries: For lightweight, custom global data/services.

Remember to carefully consider the trade-offs of increased coupling and complexity before opting for a custom approach.

常见问题解答

「自定义通信方案」课时是免费的吗?

是的 — 「自定义通信方案」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 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 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「自定义通信方案」课时需要多长时间?

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

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

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

此课程中的所有课时

  1. 跨应用通信的事件总线
  2. 共享状态管理
  3. 自定义通信方案
  4. 使用自定义 DOM 事件进行通信
← 返回 Micro Frontends Architecture with Module Federation