0Pricing
Micro Frontends Architecture with Module Federation · レッスン

カスタム通信ソリューション

特定のMicro Frontendの要件に合わせたカスタム通信メカニズムを設計・実装します。

「カスタム通信ソリューション」はCoddyKit上の無料Micro Frontends Architecture with Module Federationレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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.

よくある質問

「カスタム通信ソリューション」レッスンは無料ですか?

はい。「カスタム通信ソリューション」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Micro Frontends Architecture with Module Federationコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Micro Frontends Architecture with Module Federationコースには全4レッスンが含まれています。

「カスタム通信ソリューション」で何を学びますか?

特定のMicro Frontendの要件に合わせたカスタム通信メカニズムを設計・実装します。 ブラウザで直接実行するハンズオンコードでMicro Frontends Architecture with Module Federationを演習し、24時間対応の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に戻る