React微前端通过Webpack引入失败,远程入口配置问题排查
Module Federation配置本地Common MFE失败的问题排查
项目结构
MFE-Projects |------Packages | |---------Auth | | |------dist | | |------webpack.config.js | |---------Common | | |------dist | | |------webpack.config.js
问题场景
我需要在Auth微前端项目中引入Common微前端,已知Common的remoteEntry.js路径为D:/MFE-Projects/Packages/Common/dist/remoteEntry.js,且浏览器中通过file:///D:/MFE-Projects/Packages/Common/dist/remoteEntry.js能正常访问该文件,但配置Webpack的ModuleFederationPlugin后并未生效。
当前Webpack配置的关键部分:
const webpack = require("webpack"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const { ModuleFederationPlugin } = require("webpack").container; module.exports = { entry: "./src/index.ts", mode: "production", output: { filename: "[name].[contenthash].js", path: path.resolve(__dirname, "./dist"), publicPath: "" }, resolve: { extensions: [".ts", ".tsx", ".js"] }, // 省略其他配置 plugins: [ new webpack.DefinePlugin({ "process.env": JSON.stringify(process.env) }), new ModuleFederationPlugin({ name: "auth", filename: "remoteEntry.js", remotes: { // 尝试过以下路径但无效 // common: `common@D:/MFE-Projects/Packages/Common/dist/remoteEntry.js` common@file:///D:/MFE-Projects/Packages/Common/dist/remoteEntry.js }, exposes: { "./AuthApp": "./src/bootstrap" }, // 省略其他配置 }), new HtmlWebpackPlugin({ template: "./public/index.html" }) ] };
错误原因与修正方案
核心错误:remotes配置的语法格式错误
remotes是一个对象,必须严格遵循键名: 字符串值的格式。你当前的写法缺少键值对的正确结构,没有将路径以字符串形式赋值给common键。
正确配置写法
修正后的remotes配置如下:
remotes: { common: 'common@file:///D:/MFE-Projects/Packages/Common/dist/remoteEntry.js' },
额外注意事项
请确认Common MFE的Webpack配置中,ModuleFederationPlugin的name字段确实为"common",因为remote的格式要求是[remoteName]@[remoteEntryUrl],这里的remoteName必须与Common项目中定义的name完全一致。
内容的提问来源于stack exchange,提问作者micronyks
相关产品推荐
相关产品推荐

