How to serve images inside Remote components using Module Federation and NextJS

625 Views Asked by At

I just started to learn about module federations and started to create a POC using NextJs to see the things work.

For this, I created a component that receives a text as a param and prints this text, and show an image from my public folder

App001 - {text}
<img src="/01.png" />

When I access the local URL everything is OK.

So in my next.config I'm using the recommended plugin @module-federation/nextjs-mf to do my configuration

/** @type {import('next').NextConfig} */

const NextFederationPlugin = require('@module-federation/nextjs-mf');const nextConfig = {

  reactStrictMode: true,

  webpack: (config, options) => {

    config.plugins.push(

      new NextFederationPlugin({

        name: 'app001',

        filename: 'static/chunks/remoteEntry.js',

        exposes: {

          './component': './src/component/index.tsx'

        },

        extraOptions: {

          enableImageLoaderFix: true,

          enableUrlLoaderFix: true,

          automaticAsyncBoundary: true

        }

      }),

    );

    return config;

  }

}
module.exports = nextConfig

Inside my host, I have a similar configuration for my next.config

const NextFederationPlugin = require('@module-federation/nextjs-mf');

const nextConfig = {

  reactStrictMode: true,

  webpack: (config, options) => {

    config.plugins.push(

      new NextFederationPlugin({

        name: 'host',

        filename: 'static/chunks/remoteEntry.js',

        remotes: {

          app001: `app001@http://localhost:3001/_next/static/chunks/remoteEntry.js`,

        },

        extraOptions:{

          enableImageLoaderFix: true,

          enableUrlLoaderFix: true,

          automaticAsyncBoundary: true,

        },

      }),

    );

    return config;

  },

}
module.exports = nextConfig

And then I import this inside my home page

const SampleComponent2 = dynamic(() => import('app001/component'))

So When I run both applications I can see this component inside my host, but as the img src search for /01.png the remote tries to find this inside the host and return 404 for an image.

If I change the src for a full URL It works, but my doubt is: Can I do it more globally and apply a base URL to all my internal sources?

I tried to setup a publicUrl to this, but no changes.

tried to add a complete URL to src this work but for a big scenario, this have a lot of work

<img src="http://localhost:3001/01.png" />
0

There are 0 best solutions below