其他分享
首页 > 其他分享> > Module Federation示例

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

效果图:

 

标签:const,Federation,示例,Module,js,Header,webpack,nav,home
来源: https://www.cnblogs.com/lijun12138/p/16141941.html