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随意。

效果图:

 

posted @   lijun12138  阅读(87)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示