reactjsimagemicro-frontendsingle-spacraco

REACTJS - How to load images in a Single-Spa microfrontend built with CRACO?


I have a microfrontends application in REACT JS managed with Single SPA. All our MFE are built with webpack and created with CRA. We now want to migrate all of them to CRACO. Everything works, except for the static assets, that take the wrong URL.

By doing

import OuterSpace from '@Img/pict-space.png
[...]
console.debug(OuterSpace);
<img src={OuterSpace} />;

I correctly see in the console that the path is static/media/pict-space.2f39435387dcdab3b797.png, but the resulting url for the image doesn't start from my MFE root (which is http://localhost:3004) but takes all the url of the window.

For example: if the current route is http://localhost:3000/backoffice/1234-5678-9012/list, the computed url for my image is http://localhost:3000/backoffice/1234-5678-9012/list/static/media/pict-space.2f39435387dcdab3b797.png, that of course is a 404 not found.

How to manage this?


Solution

  • The only sensible solution, in my opinion, is to set a proxy in the server for the root-config project. This proxy would take requests for other microservices and would route them to the appropriate HTTP servers. This requires a base path to be configured for each MFE so URL's can be differentiated.

    If you are working with K8s, you are in luck: K8s is already equipped with proxies. Just define your ingresses for the MFE's using the base paths you set for each MFE and you're done.