首页 > 解决方案 > 共享组件未在主机应用程序的 SSR 中呈现

问题描述

将 SSR 与模块联合使用时出现问题。 我的代码示例

如何开始

我有两个不同的应用程序,其中一个是带有 SSR 和渲染组件逻辑的主机应用程序,第二个是带有组件的共享库。我在主机应用程序中配置了 ng-universal,并希望在加载页面时看到完整的代码响应,但我只从主机应用程序获得代码。 我的回复截图 该代码让我有机会从 remoteEntry.js 获取组件

import { LoadRemoteModuleOptions } from '../interfaces/module-federation.interfaces';

type Scope = unknown;
type Factory = () => any;

type Container = {
    init(shareScope: Scope, initScope?: Scope): void;
    get(module: string, getScope?: Scope): Promise<Factory>;
};


const createContainer = (name: string): Container => {
  // @ts-ignore
  const container = window[name] as Container;
  return container
} ;

declare const __webpack_init_sharing__: (shareScope: string) => Promise<void>;
declare const __webpack_share_scopes__: { default: Scope, plugin: Scope };

const moduleMap: any = {};

export function loadRemoteEntry(remoteEntry: string): Promise<boolean> {
    return new Promise<any>((resolve, reject) => {
        if (moduleMap[remoteEntry]) {
            resolve(moduleMap[remoteEntry]);
            return;
        }

        const script = document.createElement('script');
        script.src = remoteEntry;

        script.onerror = reject;

        script.onload = () => {
            moduleMap[remoteEntry] = true;
            resolve(moduleMap[remoteEntry]); // window is the global namespace
        };

        document.body.appendChild(script);
    });
}

async function lookupExposedRemote<T>(
    remoteName: string,
    exposedModule: string
): Promise<T> {
  // Initializes the share scope. This fills it with known provided modules from this build and all remotes
  await __webpack_init_sharing__('default');
  // @ts-ignore
  // @ts-ignore
  const container = createContainer(remoteName);
  if (!container) {throw new Error('Container with script is not defined')}
  await container.init(__webpack_share_scopes__.default);
  const factory = await container.get(exposedModule);
  const Module = factory();
  return Module as T;
}

export async function loadRemoteModule(
    options: LoadRemoteModuleOptions
): Promise<any> {
    await loadRemoteEntry(options.remoteEntry);
    return await lookupExposedRemote<any>(
        options.remoteName,
        options.exposedModule
    );
}

我认为问题是因为我在服务器端没有对象 Window,但我为此使用了多米诺骨牌。也许有人可以帮助我,我将不胜感激。

标签: javascriptangularwebpackwebpack-module-federation

解决方案


问题解决了。只需构建远程应用程序并使用 lite 服务器启动它。回购已更新。如果您需要,请使用它。 https://i.imgur.com/pkyTEsQ.png


推荐阅读