Module Federation
简单说就是提出一个模块作为“远程模块”,”本地模块“可以导入这个模块使用,同时”本地模块“也可以作为其他模块的”远程模块“
优点
- 只是作为引用, 不会参与本地模块打包,减小产物体积
- 可以做到按需加载
- 每个模块单独存在,可以单独进行开发、测试等
实践
首先说一下大概的流程:
- 新建 remote host 项目(官方是同vue,我们也是用vue)
- remote 作为远程模块,我们通过打包,预览打包后的产物来模拟上线
- host 作为本地模块,引入远程模块使用
使用 vite-plugin-federation 插件
remote 和 host 分别安装
1
| pnpm install @originjs/vite-plugin-federation -D
|
处理 remote
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| export default defineConfig({ plugins: [ vue(), federation({ name: 'remote-app', filename: 'remoteEntry.js', exposes: { './App': './src/App.vue', }, shared: ['vue'] }) ], build: { target: "esnext", }, })
|
执行打包
预览,执行前先将 package.json 的 preview 设置为 “vite preview –port=3030 –strictPort”
处理 host
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| export default defineConfig({ plugins: [ vue(), federation({ remotes: { remote_app: "http://localhost:3030/assets/remoteEntry.js", }, shared: ["vue"], }), ], build: { target: "esnext", }, })
|
使用远程模块
1 2 3 4 5 6 7 8 9 10
| <script setup> import RemoteApp from "remote_app/App"; </script>
<template> <div> <h1>Host App</h1> <RemoteApp /> </div> </template>
|
启动后效果
