Module federation using CRACO, React and typescript throws error: Module not found Can't resolve module "mfe1/Component"

Viewed 1117

craco.config.js for mfe1

const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
  
module.exports = {
    mode: 'development',
    devServer: {
        port: 9999,
    },
    plugins: 
        new ModuleFederationPlugin(
        {
            name: "mfe1",
            filename:"remoteEntry.js",
            library: {
                type: "var",
                name: "mfe1",
            },
            exposes: {
                // expose each component
                "./Component": "./src/index.tsx",
            },
        })
};

craco.config.js for mfe2


const ModuleFederation = require('webpack/lib/container/ModuleFederationPlugin');

module.exports = {
      resolve: {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
      },
      module: {
        rules: [
          {
            test: /\.tsx?$/,
            use: "ts-loader",
            exclude: /node_modules/,
          },
        ],
      },
      resolve: {
        extensions: [".tsx", ".ts", ".js"],
      },
      output: {
        publicPath: "http://localhost:3000/",
      },
      plugins: 
        new ModuleFederation({
            name: 'mfe2',
            filename: 'remoteEntry.js',
            remotes: {
                mfe1: 'mfe1@http://localhost:9999/remoteEntry.js',
            }
        }),
}
const RemoteComponent = React.lazy(()=>import("mfe1/Component"));
  1. Application contains 2 microfrontends - mfe1 and mfe2
  2. mfe1 exposes Component mfe2 imports remote component from mfe1
  3. Import throws error: Cannot find module 'mfe1/Component' or its corresponding type declarations.
1 Answers

Do not expose extension in line: "./Component": "./src/index.tsx", use simply

exposes: {
                // expose each component
                "./Component": "./src/index",
},

btw it's recommended not exposing index.tsx as the "usual" setup is index.js

import('./app/bootstrap.tsx'); //its for react + moduleFederation

bootstrap will contains the originial index.js content then bootstrap will import into the root.render.

After this you can simply expose "./Component": "./src/App".

Related