Runtime Access

Prerequisite reading

Atualmente, Module Federation fornece two formas para register e carregar módulos:

  • One é para declare it no plugin de build (geralmente no module-federation.config.ts arquivo).

  • O other way é para diretamente register e carregar módulos por meio do runtime API.

O two modes não são conflicting e pode ser usado together. Você pode flexibly choose o módulo registration método e timing according para your actual scenario.

Differences entre o two approaches

Registering módulos em runtimeRegistering módulos em o plugin
Can ser usado sem o plugin de build, e pure runtime pode ser usado directly for módulo registration e carregamento em projects like webpack4O plugin de build needs para ser webpack5 ou above
Suporta dynamic módulo registrationDoes não suporte dynamic módulo registration
Does não suporte carregamento módulos com import syntaxSuporta carregamento módulos com import synchronous syntax
Suporta carregamento módulos com loadRemoteSuporta carregamento módulos com loadRemote
Setting shared deve forneça specific versão e instance informationSetting shared apenas requires configuring rules, sem providing specific versão e instance information
shared dependências pode apenas ser usado externally, e external shared dependências cannot ser usadoshared dependências são shared bidirectionally according para specific rules
O carregamento process pode ser affected through o runtime's plugin mechanismCurrently does não suporte providing plugin para affect o carregamento process
Does não suporte remote tipo hintsSuporta remote tipo hints

If the build plugin is used, an MF instance will be automatically created and stored in memory when the project starts. You can directly call methods of the MF instance via the .

import { loadRemote } from '@module-federation/enhanced/runtime';

loadRemote('remote1');

If the build plugin is not used, you need to manually create an MF instance before calling the corresponding API.

import { createInstance } from '@module-federation/enhanced/runtime';

const mf = createInstance({
  name: 'host',
  remotes: [
    {
      name: 'remote1',
      entry: 'http://localhost:2001/vmok-manifest.json',
    },
  ],
});

mf.loadRemote('remote1');
ModuleFederation instance

An object created by the ModuleFederation class that contains all runtime functionality. You can enter __FEDERATION__.__INSTANCES__ in the console to view the full instance information.

Instalação

Different projeto tipos deve instale e importe Runtime de diferente entries. Most projetos deve instale @module-federation/enhanced e importe API de runtimes de @module-federation/enhanced/runtime. Se your Modern.js projeto já usa uma Module Federation plugin, importe API de runtimes do plugin's /runtime entry so o framework plugin e manual Runtime calls use o mesmo Runtime instance.

@module-federation/enhanced

npm
yarn
pnpm
bun
npm install @module-federation/enhanced --save
import { createInstance, loadRemote } from '@module-federation/enhanced/runtime';

Modern.js

npm
yarn
pnpm
bun
npm install @module-federation/modern-js-v3 --save
import { createInstance, loadRemote } from '@module-federation/modern-js-v3/runtime';

For Modern.js v2 projetos, instale @module-federation/modern-js e importe API de runtimes de @module-federation/modern-js/runtime.

Módulo Registration

Build Plugin(Use build plugin)
Pure Runtime(Not use build plugin)
// If use build plugin, you can use `registerRemotes` directly.
import { registerRemotes } from '@module-federation/enhanced/runtime';

registerRemotes([
  {
      name: 'remote1',
      alias: 'remote-1',
      entry: 'http://localhost:3001/mf-manifest.json',
  }
]);

Módulo Carregamento

Build Plugin(Use build plugin)
Pure Runtime(Not use build plugin)
// If use build plugin, you can use `loadRemote` directly.
import { loadRemote } from '@module-federation/enhanced/runtime';
import React from 'react';

export default () => {
  const MyButton = React.lazy(() =>
    loadRemote('remote1').then(({ MyButton }) => {
      return {
        default: MyButton
      };
    }),
  );

  return (
    <React.Suspense fallback="Loading Button">
      <MyButton />
    </React.Suspense>
  );
}

Carregamento Anonymous Módulos

Build Plugin(Use build plugin)
Pure Runtime(Not use build plugin)
// If use build plugin, you can use `loadRemote` directly.
import React from 'react';
import { loadRemote } from '@module-federation/enhanced/runtime';

const RemoteButton = React.lazy(() => loadRemote('provider/button'));
// 也可通过模块别名加载:
// const RemoteButton = React.lazy(() => loadRemote('remotes-1/button'));

export default () => {
  return (
    <React.Suspense fallback="Loading Button">
      <RemoteButton />
    </React.Suspense>
  );
}

Carregamento Named Módulos

Build Plugin(Use build plugin)
Pure Runtime(Not use build plugin)
// If use build plugin, you can use `loadRemote` directly.
import React from 'react';
import { loadRemote } from '@module-federation/enhanced/runtime';

export default () => {
  const RemoteButton = React.lazy(() =>
    loadRemote('remote1/button').then(({ RemoteButton }) => {
      return {
        default: RemoteButton
      };
    }),
  );
  return (
    <React.Suspense fallback="Loading Button">
      <RemoteButton />
    </React.Suspense>
  );
}

Carregamento Utility Funções

Build Plugin(Use build plugin)
Pure Runtime(Not use build plugin)
// If use build plugin, you can use `loadRemote` directly.
import React from 'react';
import { loadRemote } from '@module-federation/enhanced/runtime';

// 加载 remote1 expose 的 util
loadRemote<{add: (...args: Array<number>)=> number }>("remote1/util").then((md)=>{
    md.add(1,2);
});
  • Runtime API: createInstance, loadRemote, registerRemotes, e other runtime APIs.
  • Runtime Plugins: extend o carregamento em runtime flow.
  • Runtime Hooks: lifecycle hooks disponível para runtime plugins.