Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
如何用Webpack的Module Federation实现微前端?_创想鸟

如何用Webpack的Module Federation实现微前端?

答案:Webpack Module Federation 实现微前端的核心是通过 Host 应用动态加载 Remote 应用暴露的模块,并共享依赖避免重复加载。1. 角色包括 Host(主应用)、Remote(子应用)和 Shared Modules(如 React)。2. Remote 配置中使用 ModuleFederationPlugin 暴露组件,设置 name、exposes 和 shared。3. Host 配置 remotes 引入远程应用地址,并同步 shared 依赖。4. Host 可直接 import 远程模块,运行时自动加载 remoteEntry.js。需确保网络可达、配置一致,尤其注意 shared 版本和路径正确性。

如何用webpack的module federation实现微前端?

使用 Webpack 的 Module Federation 实现微前端,核心在于让多个独立的前端应用在运行时共享代码和组件。它允许一个应用(宿主)动态加载另一个应用(远程)暴露的模块,实现页面级别的集成,而无需构建时合并代码。

1. 基本概念与角色划分

Module Federation 中有三种主要角色:

Host(容器应用):主应用,负责加载其他微前端应用。 Remote(远程应用):被加载的子应用,暴露自己的模块供 Host 使用。 Shared Modules(共享依赖):如 React、Vue、Lodash 等,避免重复加载。

通过配置,Remote 暴露入口,Host 动态引用,实现松耦合集成。

2. Remote 应用配置(子应用)

在子应用的 webpack 配置中使用 ModuleFederationPlugin 暴露模块:

立即学习“前端免费学习笔记(深入)”;

new ModuleFederationPlugin({
  name: ‘app2’,
  filename: ‘remoteEntry.js’,
  exposes: {
    ‘./Button’: ‘./src/components/Button’,
    ‘./App’: ‘./src/App’,
  },
  shared: {
    react: { singleton: true },
    ‘react-dom’: { singleton: true }
  }
})

说明:

name 是远程应用唯一标识。 exposes 定义哪些模块可被外部加载。 shared 声明共享依赖,singleton: true 确保只加载一份实例。

3. Host 应用配置(主应用)

主应用引入远程模块,并声明自己可能被共享的依赖:

new ModuleFederationPlugin({
  name: ‘app1’,
  remotes: {
    app2: ‘app2@http://localhost:3002/remoteEntry.js’
  },
  shared: {
    react: { singleton: true },
    ‘react-dom’: { singleton: true }
  }
})

关键点:

remotes 指定远程应用的名称和 entry 地址。 URL 必须能访问到 remoteEntry.js 文件。 shared 配置需与 Remote 保持一致,避免版本冲突。

4. 在 Host 中使用远程组件

配置完成后,Host 可像导入本地模块一样使用远程模块:

import Button from ‘app2/Button’;

function App() {
  return (
    

      

主应用

      
    

  );
}

Webpack 会在运行时自动下载 remoteEntry.js 并解析所需模块。

基本上就这些。只要网络可达、配置匹配,就能实现跨应用模块调用。注意开发时子应用需独立启动并提供 remoteEntry.js,生产环境部署时也要确保资源路径正确。不复杂但容易忽略细节,比如 shared 版本对齐或远程地址拼写错误。

以上就是如何用Webpack的Module Federation实现微前端?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1526420.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
在 Node.js 中,如何利用性能钩子监控事件循环的延迟?
上一篇 2025年12月20日 18:31:00
从 Discord.js 14 论坛主题的起始消息中提取完整数据
下一篇 2025年12月20日 18:31:17

相关推荐

发表回复

登录后才能评论
关注微信