You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Module Federation:如何从其他微前端项目导入共享模块

在Module Federation微前端中共享原子架构的Atoms组件

要在其他微前端中复用你的atoms模块组件,核心是通过Module Federation的组件级导出/导入实现,而不局限于路由级模块。以下是具体步骤:

1. 配置提供Atoms模块的远程应用

在托管atoms模块的微前端项目中,修改Webpack的ModuleFederationPlugin配置,将atoms模块声明为可导出的资源:

// webpack.config.js
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');

module.exports = {
  // 其他配置...
  plugins: [
    new ModuleFederationPlugin({
      name: 'atomsHost', // 远程应用的唯一标识
      filename: 'remoteEntry.js', // 远程入口文件名
      // 导出你要共享的atoms模块
      exposes: {
        './atoms': './src/atoms/index', // 假设你的atoms组件都在src/atoms/index导出
      },
      // 可选:共享基础依赖(如React/Vue)避免重复打包
      shared: {
        react: { singleton: true, requiredVersion: '^18.0.0' },
        'react-dom': { singleton: true, requiredVersion: '^18.0.0' },
      },
    }),
  ],
};

确保src/atoms/index文件正确导出所有原子组件,比如:

// src/atoms/index.js
export { default as Button } from './Button';
export { default as Input } from './Input';
export { default as Avatar } from './Avatar';

2. 在消费端微前端配置远程引用

在需要使用atoms组件的微前端项目中,同样修改ModuleFederationPlugin,添加对远程atomsHost的引用:

// 消费端webpack.config.js
new ModuleFederationPlugin({
  name: 'consumerApp',
  // 配置远程应用的入口地址
  remotes: {
    atomsHost: 'atomsHost@http://localhost:3000/remoteEntry.js', // 替换为远程应用的实际地址
  },
  // 同步共享依赖配置,和远程端保持一致
  shared: {
    react: { singleton: true, requiredVersion: '^18.0.0' },
    'react-dom': { singleton: true, requiredVersion: '^18.0.0' },
  },
});

3. 在消费端直接导入并使用原子组件

配置完成后,就可以在消费端的任意组件中直接导入远程的atoms组件,和使用本地组件完全一致:

静态导入(适合确定远程模块稳定可用的场景)

// 消费端某个业务组件
import { Button, Input } from 'atomsHost/atoms';

function LoginForm() {
  return (
    <div>
      <Input placeholder="用户名" />
      <Input placeholder="密码" type="password" />
      <Button type="primary">登录</Button>
    </div>
  );
}

动态导入(推荐,处理加载失败/懒加载场景)

// 消费端某个业务组件
import { Suspense, lazy } from 'react';

const { Button, Input } = lazy(() => import('atomsHost/atoms'));

function LoginForm() {
  return (
    <Suspense fallback={<div>加载中...</div>}>
      <Input placeholder="用户名" />
      <Input placeholder="密码" type="password" />
      <Button type="primary">登录</Button>
    </Suspense>
  );
}

关键注意事项

  • 依赖版本一致性:确保所有微前端的基础依赖(如React、Vue)版本一致,通过shared配置的requiredVersion强制约束,避免运行时冲突。
  • 样式隔离与兼容:如果原子组件使用了CSS Modules、Tailwind或其他样式方案,要确保消费端的构建工具能正确解析这些样式(比如同步配置postcss、tailwind.config等)。
  • 远程地址适配:生产环境中要替换为远程应用的正式部署地址,可通过环境变量动态配置,避免硬编码。

内容的提问来源于stack exchange,提问作者Santiago Saavedra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 16:38:14