How to dynamically load microapplications with single-spa

1.6k views Asked by At

I'm trying to build a React root application that loads micro applications dynamically based on logged user role.

My root application has been created with create-react-app.

index.tsx is like this

import reportWebVitals from './reportWebVitals';
import { registerApplication, start } from 'single-spa';
registerApplication(
    'root',
    () => import('./root.app.js'),
    () => true,
);
start();
reportWebVitals();

I'm using oidc-react to manage authentication and I'm using it in this way:

import { AuthProvider } from 'oidc-react';
const oidcConfig = {....}
function App() {
  return (
      <AuthProvider {...oidcConfig} >
          <Layout />
      </AuthProvider>
  );
}

Layout component is like:

const Layout = () => {
   useEffect(()=>{
        registerDynamicApplication("http://localhost:8500/mf-video.js", "mf-container");
    }, []);

   return (
      <>
         <div id="mf-container">

         </div>
      </>
   )
};

Where registerDynamicApplication is:

export const registerDynamicApplication = (url, id, customProps = {}) => {
    let parcel = null;
    if (document.getElementById(id)) {
        parcel = mountRootParcel(() => import(url), {
            domElement: document.getElementById(id),
            ...customProps
        });
    }
    return parcel;
}

In the useEffect will be present the api call to fetch applications based on user role.

When I try to load microapplication in this way I receive error:

Uncaught (in promise) Error: Cannot find module 'http://localhost:8500/mf-video.js'
    at utils|lazy|groupOptions: {}|namespace object:5:1

The microapplication has been created with the cli command:

create-single-spa --moduleType app-parcel --framework react

without touching anything.

When I try to access http://localhost:8500/mf-video.js, I reach to get content:

enter image description here

Do you have idea why first load of mf is not working?

Thank you!

0

There are 0 answers