single-spa / single-spa-angular

Helpers for building single-spa applications which use Angular
Apache License 2.0
203 stars 78 forks source link

How to load resources (like icons) for a micrfrontend app? #518

Closed ethan-gerardot closed 6 months ago

ethan-gerardot commented 6 months ago

Question

My root app is hosted on port 9000 (https://localhost:9000). My microfrontend is on port 9001 (https://localhost:9001 and I can load it via https://localhost:9000/my-app because of how my root app is configured).

The microfrontend app has assets (icons) that it needs to be able to load. But it's trying to load them from https://localhost:9000/my-app/path/to/asset so they're coming back as 404 errors. I need it to try to load them from https://localhost:9001/my-app/path/to/asset but I can't figure out how angular builds the URL it's using to get the icons, so I don't know how to control it such that I can give it the correct port (all I provide for getting an asset is the relative path...like <img [src]="path/to/asset"/>).

I feel that I can't be the only one who has tried to do this, so there must be some way, I suspect. I'm probably missing something or not understanding how this is supposed to work.

So, how can I load resources (like icons) for a micrfrontend app that's being hosted on a different port from the root app? Or maybe I can control the URL to force it to access the icons on the right port & path...how could I do that from the microfrontend app?

Environment

Libs: Angular 17.3.7 "single-spa-angular": "^9.1.2", "zone.js": "~0.14.5"

victorlevasseur commented 6 months ago

Hi,

You need to use the assetUrl function created by the single-spa schematic in your project, as explained here: https://single-spa.js.org/docs/ecosystem-angular/#angular-assets

ethan-gerardot commented 6 months ago

Another option is to use a proxy in the root app's webpack.config.js like this:

...

module.exports = (webpackConfigEnv, argv) => {
  ...

  return merge(defaultConfig, {
    devServer: {
      proxy: [{
        context: ['/my-app/assets'],
        target: 'https://localhost:9001',
        secure: false,
        ws: true, // If you have a websocket (wss://) you want to proxy (otherwise it only proxies https://)
      }],
    },

    ...
  });
};