基于 EMP 实现 Module Federation 动态更改 Remote Host

2,759 阅读1分钟

ExternalTemplateRemotesPlugin 核心概念

  • 在运行时定义URL
  • 更好地实现版本缓存、动态缓存

具体如下

配置文件 emp-config.js

// 后续考虑收录到 packages
const ExternalTemplateRemotesPlugin = require('./ExternalTemplateRemotesPlugin')
/**
 * @type {import('@efox/emp-cli').EMPConfig}
 */
module.exports = {
  webpackChain(config) {
    //使用 ExternalTemplateRemotesPlugin
    config.plugin('ExternalTemplateRemotesPlugin').use(ExternalTemplateRemotesPlugin)
  },
  moduleFederation: {
    remotes: {
      // '@emp/demo1': 'demo1@http://localhost:8001/emp.js', //之前的代码对比
      '@emp/demo1': 'demo1@[window.demo1Url]/emp.js',
    },
  },
}

代码入口文件 src/index.ts

// demo1Url 可以增加 Math.random() or verson 等等参数来引入 
 ;(window as any).demo1Url = 'http://localhost:8001'
import('./bootstrap')

实例

image.png

总结

对于动态引用的方案、我们可以更好地利用实现各种复杂场景如:

  • 多版本
  • 清理缓存
  • 开发、正式环境切换
  • 更多 你们来写!