【问题标题】:webpack module federation + vuejs dynamic import()webpack 模块联合 + vuejs 动态导入()
【发布时间】:2021-10-14 09:36:12
【问题描述】:

我正在尝试根据路由名称动态调用某些组件。 我的组件来自远程模块联合,因此我需要保留该结构: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")));

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

【问题讨论】:

    标签: webpack vue-router vuejs3 webpack-module-federation


    【解决方案1】:

    如果在 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

    【讨论】:

      猜你喜欢
      • 2022-11-24
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      相关资源
      最近更新 更多