Microfrontend集成问题:将React子应用导入Next.js父应用时出现模块未找到错误

5kgi1eie  于 9个月前  发布在  React
关注(0)|答案(1)|浏览(91)

我目前正在使用Next.js设置一个微前端架构,其中父应用程序使用Next.js,子应用程序使用React。下面是我配置的关键细节:
//React子应用的webpack.js

const HtmlWebpackPlugin = require("html-webpack-plugin");
const { ModuleFederationPlugin } = require("webpack").container;
const path = require("path");
const deps = require("./package.json").dependencies;

module.exports = {
  entry: "./src/index.js",
  mode: "development",
  devServer: {
    static: path.join(__dirname, "dist"),
    port: 3001,
  },
  resolve: {
    extensions: [".jsx", ".js"],
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        loader: "babel-loader",
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.svg$/,
        use: ["@svgr/webpack"],
      },
    ],
  },
  plugins: [
    new ModuleFederationPlugin({
      name: "child",
      filename: "remote.js",
      exposes: {
        "./App": "./src/App",
      },
      shared: {
        react: {
          singleton: true,
          requiredVersion: deps.react,
        },
        "react-dom": {
          singleton: true,
          requiredVersion: deps["react-dom"],
        },
        next: {
          singleton: true,
          requiredVersion: deps["next"],
        },
      },
    }),
    new HtmlWebpackPlugin({
      template: "./public/index.html",
      chunks: ["main"],
    }),
  ],
};

字符串
我在遵循通常的文件结构

  • [App.js,index.js,.] // Simple React app

Next.js配置(next.js.js):
//host/next.js.js

const { NextFederationPlugin } = require("@module-federation/nextjs-mf");

const nextConfig = {
  reactStrictMode: true,
  webpack(config, { isServer }) {
    config.plugins.push(
      new NextFederationPlugin({
        name: "host",
        filename: "static/chunks/remoteEntry.js",
        remotes: {
          child: "child",
        },
        exposes: {},
      })
    );

    return config;
  },
};


当我尝试在Nextjs应用程序中导入React模块时,

import Image from "next/image";
import dynamic from "next/dynamic";
const HomePage = dynamic(() => import("child/App"), { ssr: false });

export default function Home() {
  return (
    <HomePage />
  );
}


我得到这个错误
模块未找到:无法解析“child/App”
是什么原因导致了这个“Module not found”错误,我该如何解决它,才能成功地将React子应用导入到Next.js父应用中?

tgabmvqs

tgabmvqs1#

需要从不同的区域进行排序,可能会首先检查远程名称是否真的是“child”。在您的Next.js配置(next.js.js)中,检查是否将远程配置为“child”:

remotes: {
  child: "child",
},

字符串
请确保此名称与您在子应用程序的webpack配置中定义的名称(webpack.js.js中的名称:“child”)相匹配。请仔细检查是否存在拼写错误或大小写敏感问题。如果不是此区域,请检查远程入口路径、远程模块路径.

相关问题