安装
1、新建文件夹a,执行下面命令,初始化项目,得到一个package.json文件
npm init
2、安装以下包,至于webpack的版本只要是webpack5或5以上的都行,添加build命令
yarn add webpack webpack-cli -D
//package.json
{
"name": "a",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack" // build命令
},
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1"
}
}
3、在文件夹根目录下新建一个index.js,导出变量app
4、文件夹根目录下新建webpack.config.js,简单入口配置;
//webpack.config.js
module.exports = {
entry: './index.js',
output: {
filename: 'index.[hash].js'
},
mode: 'development',
};
5、执行 npm run build ,然后看到根目录文件夹多了个dist文件夹,里面的内容就是打包生成的内容。
到这准备工作就做好了,接下来我们模拟2个团队,团队a开发组件部署到线上给团队b使用,团队b使用远程组件。
团队A
在webpack.config.js引入ModuleFederationPlugin并进行配置
//webpack.config.js
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
entry: './index.js',
output: {
filename: 'index.[hash].js'
},
mode: 'development',
plugins: [
new ModuleFederationPlugin({
name: 'teamA', // 项目b引用时的名字,很重要
filename: 'remoteA.js', //暴露的模块统一打包在这个名字,可以任意取
exposes: {
'./Aindex': './index.js', //暴露的组件
}
}),
],
};
把dist文件清空,我们再执行一下npm run build,发现多了remortA.js这个文件;
团队B
接收团队A的组件,也需要在团队B中webpack.config.js引入ModuleFederationPlugin并进行配置。
//teamB webpack.config.js
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
entry: './index.js',
output: {
filename: 'index.js'
},
mode: 'development',
plugins: [
new ModuleFederationPlugin({
name: 'teamB',
remotes: {
aa: 'teamA@http://localhost:3000/dist/remoteA.js',
/*这有两个需要注意的点:
1、注意链接前面的名称(teamA)和远程组件的name配置必须一致;
2、后面的remoteA.js是teamA里面配置的fileName。
3、key值(aa)任意取,是teamB中引入模块时的名称。
*/
},
}),
],
};
团队B项目也是在根目录下有一个index.js文件
async function test() {
const fromA = await import('aa/Aindex') //引用团队A的组件,可以分别去对应一下aa和Aindex出自哪里的配置
console.log('fromA', fromA)
}
test()
这时候我们执行一下团队B项目,可以在页面中看到组件已经引用过来了