2

我试图根据路由名称动态调用一些组件。我的组件来自远程模块联合,因此我需要保留该结构: import('module/Module') 除非有其他方法来定义它。

这是我的 webpack 配置

 new ModuleFederationPlugin({
      name: "core-front",
      remotes: {
        test: "test@http://localhost:8081/remoteEntry.js",
        test2: "test2@http://localhost:8082/remoteEntry.js",
      },
      exposes: {},
      shared: require("./package.json").dependencies,
    }),

因此,如果我的路线是 localhost:8080/app/test,我想加载 test 或 test2

我尝试动态重写名称并在 import() 中使用它,但它不起作用。

<template>
  <component :is="name"></component>
</template>

<script setup>
import {computed, defineAsyncComponent} from "vue";
import {useRoute} from "vue-router";
const route = useRoute();

const capitalizer = (string) => {
  return (string && string[0].toUpperCase() + string.slice(1)) || "";
};

const name = computed(() => {
  const appName = route.params.name;
  const appNameCapitalize = capitalizer(appName);

  return defineAsyncComponent(() => import(`${appName}/${appNameCapitalize}`));
});
</script>

我收到此错误:未捕获(承诺)错误:找不到模块“测试/测试”

(虽然模块名称是正确的......)

这有效:

const name = computed(() => defineAsyncComponent(() => import("test/Test")));

看来我们不能在导入中使用动态名称。知道如何绕过这个问题吗?我想稍后也使用公开模块的动态列表,这就是我不想硬编码名称的原因。

4

1 回答 1

0

如果在 React 中,使用下面的方法来加载动态模块,我会说它们在 VUE 中会非常相似......

function loadComponent(scope, module, baseModuleType) {
   return async () => {
    await __webpack_init_sharing__('default');
    const container = window[scope];

    await container.init(__webpack_share_scopes__.default);

    const factory = await window[scope].get(module);
    const Module = factory();
    return { default: Module[baseModuleType] };
  };
}

const Component = React.lazy(loadComponent('App2', `./components/${componentsType}`, type));
<React.Suspense fallback="Loading System">
     <Component />
</React.Suspense>

如有其他问题,请参阅以下内容:

https://webpack.js.org/concepts/module-federation/#dynamic-remote-containers

https://dev.to/waldronmatt/tutorial-a-guide-to-module-federation-for-enterprise-n5

于 2021-12-29T12:47:54.253 回答