子应用构建与加载
子应用需正确构建产物,主应用动态加载实现按需使用。
子应用构建配置
JavaScript
export default defineConfig({
build: {
target: 'esnext', # ESM 输出
minify: false, # 联邦模式建议不压缩
cssCodeSplit: false, # CSS 不分割
outDir: 'dist',
lib: false # 不使用库模式
}
})
注意:Module Federation 需要 ESNext 格式,不压缩便于调试。
暴露模块配置
JavaScript
federation({
name: 'subApp',
filename: 'remoteEntry.js',
exposes: {
'./components/Button': './src/components/Button.vue',
'./pages/Home': './src/pages/Home.vue',
'./utils': './src/utils/index.ts'
}
})
主应用动态加载
JavaScript
// 预加载远程入口
await import('subApp/remoteEntry')
// 按需加载模块
async function loadRemoteModule() {
const Button = await import('subApp/components/Button')
return Button
}
异步组件加载
vue
<script setup>
import { defineAsyncComponent } from 'vue'
// 动态加载远程组件
const RemoteButton = defineAsyncComponent(() =>
import('subApp/components/Button')
)
</script>
<template>
<RemoteButton />
</template>
加载错误处理
JavaScript
// 模块加载失败处理
try {
const module = await import('subApp/utils')
} catch (error) {
console.error('Remote module load failed:', error)
// 使用本地 fallback
const module = await import('./local-utils')
}
加载策略对比
| 策略 | 说明 | 适用场景 |
|---|---|---|
| 预加载 | 提前加载入口 | 需快速响应 |
| 懒加载 | 使用时加载 | 非核心模块 |
| 缓存加载 | 利用浏览器缓存 | 二次访问 |
加载流程
JavaScript
主应用启动
→ 加载 remoteEntry.js(入口)
→ 解析 exposes 映射
→ 用户访问模块
→ 动态 import 模块
→ 返回模块内容
加载优化
text
// 预加载关键远程模块
federation({
remotes: {
subApp: {
external: 'subApp',
shareScope: 'default',
// 预加载配置
eager: true
}
}
})
要点总结
- 子应用构建 target 设为 esnext
- exposes 暴露模块路径映射
- 主应用使用异步 import 加载
- 加载失败使用本地 fallback
📝 发现内容有误?点击此处直接编辑