文章目录
- 一文大白话讲清楚webpack进阶——9——ModuleFederation实战
- 1. 啥是ModuleFederation
- 2. 创建容器应用
- 3. 创建远程应用
- 4. 启动远程应用
- 5. 使用远程应用的组件
一文大白话讲清楚webpack进阶——9——ModuleFederation实战
1. 啥是ModuleFederation
- 先看这篇文章,了解ModuleFederation
- 一文大白话讲清楚webpack进阶——8——Module Federation
2. 创建容器应用
- 创建项目并初始化,
- 安装webpack和webpack-cli
- 配置webpack.config.js
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const path = require("path");
module.exports = {
entry: './src/index.js',
mode: 'development',
output: {
publicPath: 'auto',
},
plugins: [
new ModuleFederationPlugin({
name: "sharedLib",
filename: "remoteEntry.js",
exposes: {
'./MyComponent': './src/MyComponent.js',
},
shared: {
react: { singleton: true, requiredVersion: '^17.0.0' },
'react-dom': { singleton: true, requiredVersion: '^17.0.0' }
}
}),
],
};
3. 创建远程应用
- 创建项目并初始化,
- 安装webpack和webpack-cli
- 配置webpack.config.js
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const path = require("path");
module.exports = {
entry: './src/index.js',
mode: 'development',
output: {
publicPath: 'auto',
},
plugins: [
new ModuleFederationPlugin({
name: "app",
remotes: {
sharedLib: "sharedLib@http://localhost:3000/remoteEntry.js",
},
shared: {
react: { singleton: true, requiredVersion: '^17.0.0' },
'react-dom': { singleton: true, requiredVersion: '^17.0.0' }
}
}),
],
};
4. 启动远程应用
5. 使用远程应用的组件
import React from 'react';
import ReactDOM from 'react-dom';
import MyComponent from 'sharedLib/MyComponent';
import App from './App';
ReactDOM.render(<React.StrictMode><App /><MyComponent /></React.StrictMode>, document.getElementById('root'));