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

Single-SPA如何从独立JSON加载import maps并在EJS模板导入配置

Single-SPA项目EJS模板导入JSON路由配置解决方案

你不需要找single-spa本身的render方法——single-spa是运行时微前端框架,不负责EJS模板的编译渲染,模板渲染能力是你的项目构建工具(webpack/vite)提供的,以下是两种可直接落地的实现方案:

方案1:通过webpack配置注入JSON(推荐,兼容性最好)

create-single-spa生成的项目默认用html-webpack-plugin处理EJS模板,可通过该插件的参数直接把JSON配置注入到模板上下文:

  • 步骤1:在项目根目录新建独立的MFE路由配置文件mfe-routes.json,示例结构如下:
[
  {
    "appName": "@your-org/mfe-home",
    "activeRule": "/home",
    "entryUrl": "https://your-cdn.com/mfe-home/v1.0.0/main.js"
  },
  {
    "appName": "@your-org/mfe-market",
    "activeRule": "/market",
    "entryUrl": "https://your-cdn.com/mfe-market/v1.2.1/main.js"
  }
]
  • 步骤2:修改项目根目录的webpack.config.js,导入JSON文件并注入到模板参数:
const singleSpaDefaults = require("webpack-config-single-spa");
const mfeRoutes = require("./mfe-routes.json");

module.exports = (webpackConfigEnv, argv) => {
  const defaultConfig = singleSpaDefaults({
    orgName: "your-org",
    projectName: "root-config",
    webpackConfigEnv,
    argv,
  });

  // 给html-webpack-plugin新增注入参数
  defaultConfig.plugins.forEach((plugin) => {
    if (plugin.constructor.name === "HtmlWebpackPlugin") {
      plugin.options.templateParameters = {
        ...plugin.options.templateParameters,
        // 把路由配置注入到ejs模板的全局变量
        mfeRoutes,
      };
    }
  });

  return defaultConfig;
};
  • 步骤3:在index.ejs中直接使用注入的mfeRoutes变量,批量生成路由和导入映射:
<!-- 批量生成SystemJS导入映射 -->
<script type="systemjs-importmap">
  {
    "imports": {
      <% mfeRoutes.forEach((route, index) => { %>
        "<%= route.appName %>": "<%= route.entryUrl %>"<%= index === mfeRoutes.length -1 ? '' : ',' %>
      <% }) %>
    }
  }
</script>

<!-- 批量注册微应用 -->
<script>
  import { registerApplication, start } from 'single-spa';
  import { pathToRegexp } from 'path-to-regexp';

  <% mfeRoutes.forEach(route => { %>
    registerApplication({
      name: "<%= route.appName %>",
      app: () => System.import("<%= route.appName %>"),
      activeWhen: pathToRegexp("<%= route.activeRule %>")
    });
  <% }) %>

  start();
</script>

方案2:EJS模板内直接require导入(无需改构建配置)

如果你的项目EJS loader默认开启了Node API支持,可直接在EJS文件顶部导入JSON文件,无需修改webpack配置:

<%# 开头直接导入同目录下的JSON文件 %>
<% const mfeRoutes = require('./mfe-routes.json') %>

<!-- 后续遍历生成路由的逻辑和方案1完全一致 -->

注意:如果导入时报错,说明你的构建配置关闭了EJS的Node API权限,切回方案1即可正常使用。

内容的提问来源于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.04 20:57:00