微前端架构-微前端qiankun详解(Qiankun)

微前端架构凭借其优秀的扩展性和隔离性,成为近年来前端架构设计的热门话题。在众多微前端框架之中,微前端qiankun脱颖而出,凭借其灵活的架构和出色的性能,已经成为了企业级微前端框架中的“排头兵”。本文将从微前端qiankun的官方文档、子应用通信、实战、原理、沙箱、wujie emp、教程、公共组件封装、图片等方面进行详细阐述。

一、微前端qiankun官网

微前端qiankun的官方文档是我们了解这个框架的最基本资料,官网包含了框架的基本知识、核心概念、使用方法、技术细节等内容。通过对官网文档的深入了解,可以让我们更好地理解qiankun的设计原理和实现方法,对于后续的开发和维护工作具有重要意义。以下是其中的一个范例,实现了一个简单的基于微前端架构的首页展示。

“`

qiankun index

hello qiankun

<script src="//unpkg.com/qiankun"></script>
<script>
qiankun.loadMicroApp(
{ name: ‘vueApp’, entry: ‘//localhost:7100’, container: ‘#root’}
);
qiankun.loadMicroApp(
{ name: ‘reactApp’, entry: ‘//localhost:7200’, container: ‘#root’}
);
</script>

“`

二、微前端qiankun子应用通信

在微前端架构中,每个应用都可以作为一个独立的子应用存在,这些子应用可以相互通信,从而达到整体协同的目的。微前端qiankun提供了多种方式来实现子应用之间的通信,包括基于props的直接传参、基于LocalStorage的数据存储、基于emit的自定义事件等。以下是qiankun中子应用之间基于props的直接传参实现的代码片段。

“`
// 父应用入口文件 main.js 中传入参数
qiankun.loadMicroApp(
{ name: ‘vueApp’, entry: ‘//localhost:7100’, container: ‘#root’, props: { username: ‘Tom’ } }
);

// 子应用 vueApp 中的代码片段,接收来自父应用的参数

hello, {{ $props.username }}!

“`

三、微前端qiankun实战

微前端qiankun不仅提供了良好的理论框架,同时也支持实际开发中的各种场景。下面是一个实际项目中的qiankun示例应用,包括一个vue和一个react应用,以及一个基于qiankun实现的基础架构模板。

基础架构模板

“`
// qiankun.js

import { registerMicroApps, start } from ‘qiankun’;
function render({ appContent, loading }) {
const container = document.getElementById(‘container’);
ReactDOM.render(loading ? : appContent, container);
}
function genActiveRule(routerPrefix) {
return (location) => location.pathname.startsWith(routerPrefix)
}
function initApp() {

const apps = [
{
name: ‘vueApp’,
entry: ‘//localhost:7100’,
container: ‘#container’,
activeRule: genActiveRule(‘/vue’)
},
{
name: ‘reactApp’,
entry: ‘//localhost:7200’,
container: ‘#container’,
activeRule: genActiveRule(‘/react’)
}
];
registerMicroApps(
apps,
{
beforeLoad: [
(app) => {
console.log(‘[qiankun] before load app.name’, app.name);
},
],
beforeMount: [
(app) => {
console.log(‘[qiankun] before mount app.name’, app.name);
},
],
afterUnmount: [
(app) => {
console.log(‘[qiankun] after unmount app.name’, app.name);
},
],
},
);
start({
sandbox: {
strictStyleIsolation: true,
},
prefetch: ‘all’,
jsSandbox: true,
singular: false,
fetch: window.fetch,
});

}
“`

Vue子应用

“`
// /vue/main.js

import Vue from ‘vue’
import App from ‘./App.vue’
import router from ‘./router’
import store from ‘./store’

Vue.config.productionTip = false

let instance = null;
function render(props = {}) {
const { container } = props;
console.log(props.appContent,’我是navbar收到的appcontent’)
instance = new Vue({
router,
store,
render: h => h(App),
}).$mount(container ? container.querySelector(‘#app’) : ‘#app’);
}
if (!window.__POWERED_BY_QIANKUN__) {
render();
}
export async function bootstrap() {
console.log(‘[vue] vue app bootstraped’);
}
export async function mount(props) {
console.log(‘[qiankun] vue app mount’, props);
render(props);
}
export async function unmount() {
console.log(‘vue app unmount’);
instance.$destroy();
instance = null;
}
“`

React子应用

“`
// /react/App.js

import React, { Component } from ‘react’;
import ‘./App.css’;

class App extends Component {
state = {
auth: {},
};

componentDidMount() {
const { onGlobalStateChange } = this.props;
// 注册监听
onGlobalStateChange((value, prev) => {
console.log(‘[onGlobalStateChange – master]:’, value, prev);
this.setState({auth: value.user_login_info})
}, true);
}

render() {
return (

当前用户:{this.state.auth?.username}

);
}
}

export default App;
“`

四、微前端qiankun原理

微前端qiankun的主要原理是利用浏览器本身的能力,将不同的子应用封装为独立的JS文件,通过重写浏览器的路由器,从而实现不同子应用之间URL的隔离和切换。在子应用中,需要对一些全局变量、事件、组件命名等方面进行额外的适配,才能保证子应用能够顺利地融入问题。以下是qiankun原理的部分代码示例,主要是对于路由的操作:

“`
import { createHashHistory } from ‘history’;

export default function getMicroAppRouter(prefix) {
const history = createHashHistory();
function listener() {
const location = history.location;
const matched = location.pathname.startsWith(
`${prefix}`
);
console.log(“再次渲染子应用了matched=”, matched)
if (matched) {
console.log(“matched真:”, location.pathname, prefix);
history.replace(location.pathname.replace(`${prefix}`, ”));
console.log(“history.rep”, history, matched, location, location.pathname);
}
}

const matches = pathname =>
pathname === prefix || pathname.startsWith(`${prefix}/`);

const router = {
basename: prefix,
push: (url, state) => history.push(`${prefix}${url}`, state),
replace: (url, state) => history.replace(`${prefix}${url}`, state),
go: history.go,
goBack: history.goBack,
goForward: history.goForward,
block: history.block,
listen: cb => history.listen(location => {
listener();
cb({
…location,
pathname: location.pathname.replace(prefix, ”),
matches: matches(location.pathname.replace(prefix, ”)),
})
}),
location: {
…history.location,
pathname: history.location.pathname.replace(prefix, ”),
matches: matches(history.location.pathname.replace(prefix, ”)),
}
};
return router;
}
“`

五、微前端qiankun沙箱

微前端中可能存在多个子应用之间使用相同库文件且版本不一致的情况,为了避免这些库文件间的相互干扰和污染,qiankun配备了一个基于IFrame的沙箱Sandbox技术,实现了真正意义上的代码隔离和运行环境隔离。以下是基于qiankun的Sandbox实现方式的代码示例。

“`
function createSandbox(container, strictStyleIsolation, appName) {
console.log(‘仔细看createSandbox内的container:’, container)
const iframe = window.document.createElement(‘iframe’);
iframe.setAttribute(‘src’, ‘about:blank’);
iframe.setAttribute(‘sandbox’, ‘allow-scripts’);
iframe.setAttribute(‘scrolling’, ‘auto’);
iframe.setAttribute(
‘style’,
`width:100%;height:100%;border:none;${
strictStyleIsolation ? ‘all:initial;’ : ”
}`
);
iframe.setAttribute(‘name’, `__qiankun_microapp_${appName}`);
container.appendChild(iframe);
const frame = iframe.contentWindow;
const sandbox = strictStyleIsolation ? window : frame;
return {
iframe,
sandbox,
active() {
iframe.style.display = ”;
},
inactive() {
iframe.style.display = ‘none’;
},
remove() {
container.removeChild(iframe);
},
update() {
const prevActive = iframe.style.display !== ‘none’;
iframe.setAttribute(
‘style’,
`width:100%;height:100%;border:none;${
strictStyleIsolation ? ‘all:initial;’ : ”
}`
);
if (prevActive) {
iframe.style.display = ”;
}
},
};
}
“`

六、微前端qiankun wujie emp

微前端qiankun作为前端架构的一种新兴技术,具有广泛的应用场景和可贵的开发经验。wujie emp作为企业级微前端系统中的优秀实践之一,为qiankun的生态发展和推广做出了重大贡献。以下是wujie emp团队对于qiankun的初步探索和实践方案分享。

“`
import React from ‘react’;
import ReactDOM from ‘react-dom’;
import { Provider } from ‘react-redux’;
import singleSpaReact from ‘single-spa-react’;
import { Router, Route } from ‘react-router-dom’;
import { createBrowserHistory } from ‘history’;
import Menu from ‘./container/Menu’
import Messages from ‘./container/Messages’
import Chat from ‘./container/Chat’
import store from ‘./store’;

function App() {
return (

);
}

const reactLifecycles = singleSpaReact({
React,
ReactDOM,
rootComponent: App,
domElementGetter,
});

export const { bootstrap, mount, unmount } = reactLifecycles;
“`

七、微前端qiankun教程

微前端qiankun逐渐成为前端架构中的重要一环,对于前端开发人员而言,掌握qiankun相关的知识和技术无疑具有很大的优势,能够在工作中更好地利用这一技术,提高开发效率并优化产品效果。以下是一篇qiankun基础教程的示例,包括了如何初始化一个qiankun应用以及如何使用qiankun管理和加载子应用。

“`
// 主应用入口文件 index.js

import ‘./public-path’;
import { registerMicroApps, start } from ‘qiankun’;

registerMicroApps([{
name: ‘subApp1’,
entry: ‘//localhost:7100’,
container: ‘#sub-app1’,
active

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注