Webpack模块联邦+Vue.js动态import()

3
我正在尝试根据路由名称动态调用一些组件。我的组件来自于远程模块联邦,所以我需要保持这种结构: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,我希望进行负载测试或测试2。

我尝试动态重写名称并在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>

我遇到了这个错误: Uncaught (in promise) Error: 找不到模块'test/Test'(模块名称是正确的...)
以下代码可以正常工作:
const name = computed(() => defineAsyncComponent(() => import("test/Test")));

似乎我们无法在导入中使用动态名称。 有什么办法可以绕过这个问题吗?我想以后也可以使用动态列表的模块,这就是为什么我不想硬编码名称。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接