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

如何从single-spa vanilla工具模块导出函数并在React MFE中导入

核心问题解答

你需要将vanilla utility module添加到root-config的import maps中。single-spa的公共import maps是所有微应用共享的模块解析规则表,只有在这里注册了工具模块的地址,其他微应用运行时才能通过模块名正确找到对应的远程资源。如果你不想全局共享,也可以单独在react MFE自己的import maps中配置,但公共工具模块更推荐放在全局import maps中统一管理。

步骤1:在vanilla utility module中导出函数

直接在工具模块的入口文件中正常导出你需要共享的内容即可,示例如下:

// src/single-spa-util-module-vanilla.js (你的工具模块入口文件)
// 导出函数
export const calculatePrice = (originPrice, discount) => originPrice * discount;
export const getSystemVersion = () => "v1.2.0";

// 也支持导出常量、对象、类等
export const SYSTEM_NOTICE = "系统将于本周日0点进行维护";
export const userHelper = {
  checkLogin: () => !!localStorage.getItem("token"),
  logout: () => localStorage.removeItem("token")
}

完成代码编写后正常打包,single-spa的工具模块模板默认会将产物打包为符合systemjs规范的模块文件,你只需要拿到打包后部署的远程js文件地址即可(本地开发时可以用本地服务的地址,比如http://localhost:8083/single-spa-util-module-vanilla.js)。

步骤2:在root-config的import maps中注册模块

找到root-config项目中的import maps配置(一般在src/index.ejs的<script type="systemjs-importmap">标签内),添加模块映射规则:

{
  "imports": {
    // 你原有其他模块的映射规则
    "@your-org/vanilla-util": "https://your-deploy-domain.com/single-spa-util-module-vanilla.js"
  }
}

模块名@your-org/vanilla-util可以自定义,只要后续导入时保持一致即可。

步骤3:在react MFE中导入使用

首先需要修改react MFE的webpack配置,将该工具模块设为外部依赖,避免重复打包:

// webpack.config.js
module.exports = {
  // 其他原有配置
  externals: ["@your-org/vanilla-util"]
}

之后就可以在react的业务代码中直接导入使用:

import { calculatePrice, getSystemVersion, userHelper } from "@your-org/vanilla-util";

function GoodsCard() {
  const price = calculatePrice(299, 0.8);
  const isLogin = userHelper.checkLogin();

  return (
    <div>
      <h3>商品价格:{price}元</h3>
      <p>系统版本:{getSystemVersion()}</p>
      <p>登录状态:{isLogin ? "已登录" : "未登录"}</p>
    </div>
  )
}

export default GoodsCard;

内容的提问来源于stack exchange,提问作者sravan ganji

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:24:02