Module Federation示例
开启三个服务,nav,home,common
1:nav的webpack.config.js配置
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {ModuleFederationPlugin} = require('webpack').container
module.exports={
mode:'development',
entry:'./src/index.js',
plugins:[
new HtmlWebpackPlugin(),
new ModuleFederationPlugin({
name:'nav',//该组件名称
filename:'remoteEntry.js',//被其它组件引用时使用
remotes:{},//需要引入的组件
exposes:{//需要暴露的组件
'./Header':'./src/nav.js'
},
shared:{}//共享组件
})
]
}
nav.js
const Header = ()=>{ const header = document.createElement('h1') header.textContent = '我是头部信息' return header } module.exports={Header}
2:home的webpack.config.js配置
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {ModuleFederationPlugin} = require('webpack').container
module.exports={
mode:'development',
entry:'./src/index.js',
plugins:[
new HtmlWebpackPlugin(),
new ModuleFederationPlugin({
name:'home',
filename:'remoteEntry.js',
remotes:{},
exposes:{
'./homeList':'./src/homeList.js'
},
shared:{}
})
]
}
homeList.js
const Home = (num)=>{ let str = "<ul>" for(let i=0;i<num;i++){ str+=`<li>item${i}</li>` } str+="</ul>" return str } module.exports={Home}
3:common的webpack.config.js配置
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {ModuleFederationPlugin} = require('webpack').container
module.exports={
mode:'development',
entry:'./src/index.js',
plugins:[
new HtmlWebpackPlugin(),
new ModuleFederationPlugin({
name:'common',
filename:'remoteEntry.js',
remotes:{
nav:'nav@http://localhost:3003/remoteEntry.js',//引入组件
home:'home@http://localhost:3002/remoteEntry.js'
}
})
]
}
index.js
import('nav/Header')
.then((Header)=>{
console.log(Header)
document.body.appendChild(Header.Header())
})
import('home/homeList')
.then((homeList)=>{
const div = document.createElement('div')
div.innerHTML=homeList.Home(5)
document.body.appendChild(div)
})
分别开启三个服务器,其中nav开启localhost:3003对应 nav:'nav@http://localhost:3003/remoteEntry.js',home开启localhost:3002对应 home:'home@http://localhost:3002/remoteEntry.js',common随意。
效果图:


浙公网安备 33010602011771号