qiankun搭建微前端步骤
# qiankun搭建微前端步骤
- 主应用
import {
registerMicroApps,
start,
} from 'qiankun';
registerMicroApps([
{
name: 'testAdmin',
entry: '//localhost:3001', // 子应用host
container: '#testAdmin', // 子应用挂在的dom节点
activeRule: '/#/v/testAdmin' // 匹配的路由
},
]);
start({
prefetch: false, // 取消预加载
sandbox: {
experimentalStyleIsolation: true //隔离样式
},
// 可以对入口html做操作
getTemplate(tpl) {
// tpl 入口html内容
return tpl.replace('', '');
},
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- 子应用 2.1 修改index.js 文件添加生命周期函数
// 修改运行时webpack __webpack_public_path__
if (window.__POWERED_BY_QIANKUN__) {
// eslint-disable-next-line no-undef
__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}
function render(props) {
const { container } = props;
ReactDOM.render(<Provider store={store}>
<App />
</Provider>,
// 区分子应用挂载的dom元素
container ? container.querySelector('#root') : document.querySelector('#root'));
}
if (!window.__POWERED_BY_QIANKUN__) {
// 没有主应用环境
render({});
}
export async function bootstrap() {
console.log('[react17] react app bootstraped');
}
export async function mount(props) {
console.log('[react17] props from main framework', props);
render(props);
}
export async function unmount(props) {
const { container } = props;
ReactDOM.unmountComponentAtNode(container ? container.querySelector('#root') : document.querySelector('#root'));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2.2 修改webpack output配置
// webpack 5 配置
config.output.library = `${name}-[name]`;
config.output.libraryTarget = 'umd';
config.output.chunkLoadingGlobal = `webpackJsonp_${name}`;
config.output.globalObject = 'window';
// 解决主应用访问子应用图片路径问题
config.output.publicPath = '子应用部署的服务。如://localhost:3001/';
1
2
3
4
5
6
7
2
3
4
5
6
7
2.3 修改代理。
// 开发环境
config.headers = {
'Access-Control-Allow-Origin': '*',
};
// 正式环境使用nginx配置允许跨域
server {
listen 3001;
server_name localhost;
add_header 'Access-Control-Allow-Origin' '主应用服务地址';
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
2.3 子应用路由修改
// 添加子应用的basename为主应用的
<Router basename={window.__POWERED_BY_QIANKUN__ ? '/main' : '/'}>
</Router>
1
2
3
2
3
- 主/子应用通信
// 主应用
import {
initGlobalState
} from 'qiankun';
const actions = initGlobalState({});
// 设置状态
action.setGlobalState({});
actions.onGlobalStateChange((state, prev) => {
// state: 变更后的状态; prev 变更前的状态
})
// 子应用
export async function mount(props) {
props.onGlobalStateChange((state, prev) => {
// state: 变更后的状态; prev 变更前的状态
});
// 设置状态
props.setGlobalState()
render(props);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- 注意事项 4.1 主/子应用需要相同的路由模式(Hash或者Browser) 4.2
// 主应用路由需要添加通配符
{
path: 'testAdmin/*',
}
// 子应用设置basename为主应用的路由前缀
<Router basename={window.__POWERED_BY_QIANKUN__ ? '/testAdmin' : '/'}>
</Router>
1
2
3
4
5
6
7
2
3
4
5
6
7