Vuejs Module Federation dynamic import

Viewed 16

I'm trying to develop microfrontend with Vuejs and Module Federation. So, i have method loadModule, that returns me a an object(maybe component), but what i should do with it i don't know. I tried to import this component like defineAsyncComponent but it's useless.

And i'm tried use the render function in this object and paste this it to markup. The screenshot shows what the object I get, but I don’t know what to do next with it and how to register this like component.

I'm stumped, any advice would be welcome

<script setup>
import { ref, onMounted, defineAsyncComponent, h } from 'vue'

import TestComp from './TestComp.vue'
let Header
const modules = [
  {
    protocol: 'http',
    host: 'localhost',
    port: 8080,
    moduleName: 'Company',
    fileName: 'remoteEntry.js',
    componentNames: ['Header'],
  },
]

onMounted(() => {
  modules.forEach((uiApplication) => {
    const remoteURL = `${uiApplication.protocol}://${uiApplication.host}:${uiApplication.port}/${uiApplication.fileName}`

    const { componentNames } = uiApplication
    const { moduleName } = uiApplication
    const element = document.createElement('script')
    element.type = 'text/javascript'
    element.async = true
    element.src = remoteURL

    element.onload = () => {
      componentNames?.forEach((componentName) => {
        const component = loadComponent(moduleName, `./${componentName}`)

        component().then((res) => {
          Header = res
          console.log(res)
          // what should i do next?

          // This is not working
          // Header = defineAsyncComponent(() => import('Company/Header'))
        })
      })
    }
    document.head.appendChild(element)
  })
})[enter image description here][1]


function loadComponent(scope, module) {
  return async () => {
    // Initializes the shared scope. Fills it with known provided modules from this build and all remotes
    await __webpack_init_sharing__('default')
    const container = window[scope] // or get the container somewhere else
    // Initialize the container, it may provide shared modules
    await container.init(__webpack_share_scopes__.default)
    const factory = await window[scope].get(module)
    const Module = factory()
    return Module
  }
}
const remoteImport = async (location, name, options) => {
  const module = await importResource(location, options)
  if (name) {
    let m = module[name]
    if (!m) {
      throw new Error(
        `No component named ${name} founded in component ${location}`
      )
    }
    return module[name]
  } else {
    return module
  }
}
</script>
<template>
  <div>
    <Header ref="Header" title="Test shop" />
    <h2>Our Shop Page</h2>
  </div>
</template>
0 Answers
Related