What is qiankun :
Based on single-spa
secondary development, it is a microservice -like architecture that splits a large application into several smaller, simpler sub-applications that can be independently developed, tested and deployed, and then a base application based on Routing for application switching is mainly proposed to solve the difficulties of large-scale projects in terms of change, maintenance, and expansion!
Advantages of qiankun:
1. Good technical compatibility, each sub-application can be based on different technical architectures;
2. The access method allows you to access the micro-app as easily as using an iframe;
3. The coupling is lower, and each team can develop independently without interfering with each other;
4. Better maintainability and scalability, which is convenient for partial upgrade and incremental upgrade;
5. JS sandbox to ensure that global variables/events do not conflict between micro-apps;
Disadvantages of qiankun:
1. Unable to support multi-instance scenarios;
2. It is very unfriendly to vite, and a lot of code needs to be changed;
3. The resource sharing ability between sub-applications is poor, which makes the total project volume larger;
4. Developers have to deal with the complexity of distributed systems;
5. The overall project size is relatively large, and the running service is sometimes slow;
My qiankun directory structure:
Create the main application:
mkdir qiankun(可自定义文件名)
//创建文件
cd qiankun
//进入文件
vue create qiankun-base(可自定义文件名)
//创建vue项目
cd qiankun-base
//进入创建好的项目
npm i qiankun -s
//进入项目下载qiankun
npm run serve
//起服务
1. Pay attention when vue create qiankun-base :
1. Manually select the version (it is best to choose manual)
2. Check the functions required by the project (it is best not to choose linter/formatter, this is ESlint)
3. Select the Vue.js version to start the project
4. Use history mode for routers
5. Choose a css preprocessor (be sure to choose scss, otherwise it will be very troublesome to use later)
6. Where do you like to put babel
7. Save it as a preset for future projects
8. Open the project, enter the project, start the project cd main ( file name ) , after entering, download npm i qiankun –s , and then npm run serve ( start service ) ! This step is indispensable!
2. The vue and js files that need to be changed:
1. Open the main.js under the file src and follow the steps below (to download and mount the element ui back menu to use):
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import {registerMicroApps, start} from 'qiankun';
// 引入qiankun里的两个方法
Vue.config.productionTip = false
Vue.use(ElementUI);
const apps = [
{
name: 'vueApp', // 应用的名字
// 一定要跟你你创建的项目的名称一致
entry: 'http://localhost:10000/', // 默认加载这个html,解析里面的js动态的执行(子应用必须支持跨域,内部使用的是 fetch)
// 其实就是你其他子应用抛出的端口名
container: '#vue', // 要渲染到的容器名id
// 你在主应用中创建的dom元素名
activeRule: '/vue' ,// 通过哪一个路由来激活
// 这个是子应用的路径
sandbox: {
strictStyleIsolation: true // 开启样式隔离
}
},
{
name: 'reactApp',
entry: 'http://localhost:20000/',
container: '#react',
activeRule: '/react',
sandbox: {
strictStyleIsolation: true // 开启样式隔离
}
},
{
name: 'tabltest',
entry: 'http://localhost:5501/',
container: '#vue2',
activeRule: '/vue2',
sandbox: {
strictStyleIsolation: true // 开启样式隔离
}
}
];
registerMicroApps(apps); // 注册应用
start(); // 开启应用
new Vue({
router,
render: h => h(App)
}).$mount('#app')
2. App.vue under the file src follows the operation : ( Note ) Do not add id , class or other pre-selectors to the outer div box :
<template>
<div style="display:flex;">
<!-- <div class="left"> -->
<el-menu :router="true" class="el-menu-vertical-demo" style="width: 15%;">
<el-submenu index="1">
<template slot="title">
<i class="el-icon-location"></i>
<span slot="title">乾坤架构</span>
</template>
<el-menu-item-group>
<el-menu-item index="/vue">xx模块</el-menu-item>
<el-menu-item index="/react">xx模块</el-menu-item>
<el-menu-item index="/vue2">xx模块</el-menu-item>
<el-menu-item index="/">xx模块</el-menu-item>
</el-menu-item-group>
</el-submenu>
</el-menu>
<!-- </div> -->
<!-- <div class="right"> -->
<router-view v-show="$route.name"></router-view>
<div id="vue"></div>
<div id="react"></div>
<div id="vue2"></div>
</div>
<!-- </div> -->
</template>
<style >
html,body{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.el-menu-vertical-demo:not(.el-menu--collapse) {
width: 200px;
min-height: 400px;
}
</style>
The main application needs to operate and it is over!
Create a vue sub-application:
cd..
//外层主应用的外层
vue create qiankun-vue
//创建子应用
cd qiankun-vue
//进入子应用
npm run serve
//启动服务
Note: sub-apps do not need to download qiankun
1. Operations on vue sub-applications:
1. Please learn how to download the main application;
2. Open and enter main.js under src in the downloaded sub-application ;
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
let instance = null;
function render(props) {
// props 组件通信
instance = new Vue({
router,
render: h => h(App)
}).$mount('#app') // 这里是挂载到自己的HTML中,基座会拿到这个挂载后的HTML,将其插入进去
}
if (!window.__POWERED_BY_QIANKUN__) { // 如果是独立运行,则手动调用渲染
render();
}
if(window.__POWERED_BY_QIANKUN__){ // 如果是qiankun使用到了,则会动态注入路径
__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}
// 根据 qiankun 的协议需要导出 bootstrap/mount/unmount
export async function bootstrap(props) {
};
export async function mount(props) {
render(props);
};
export async function unmount(props) {
instance.$destroy();
};
3. Enter vue.config.js in the sub-application (if there is no vue.config.js, create such a js file);
module.exports = {
devServer: {
port: 10000,
headers:{
'Access-Control-Allow-Origin': '*' // 允许跨域
}
},
configureWebpack: {
output: {
library: 'vueApp',
libraryTarget: 'umd'
}
}
};
4. Open and enter the index.js under the router file under src in the downloaded sub-application (you cannot switch without changing the routing of sub-applications in the main application);
const router = new VueRouter({
mode: 'history',
// qiankun这里也需要改变子应用的路径变化不对
base: '/vue',
routes
})
The above is the file and its code to be changed by the vue sub-application!
Create a react sub-app:
cd..
//回退到qiankun文件夹中(如果在就不必做此操作)
npx create-react-app qiankun-react
//创建react项目
cd qiankun-react
//进入react项目中
npm start
//起服务
Note: sub-apps do not need to download qiankun
1. Operations on react sub-applications:
1. Enter the command npx create-react-app reactapp in the terminal;
npx create-react-app qiankun-react
2. Find the index.js configuration arrow under src and the following methods;
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
function render(){
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
}
if(!window.__POWERED_BY_QIANKUN__){
render();
}
export async function bootstrap(){
}
export async function mount() {
render()
}
export async function unmount(){
ReactDOM.unmountComponentAtNode( document.getElementById('root'));
}
3. Find the configuration in the config-overrides.js file. If there is no file config-overrides.js created;
module.exports = {
webpack:(config)=>{
config.output.library = 'reactApp';
config.output.libraryTarget = 'umd';
config.output.publicPath = 'http://localhost:20000/';
return config;
},
devServer:(configFunction)=>{
return function (proxy,allowedHost){
const config = configFunction(proxy,allowedHost);
config.headers = {
"Access-Control-Allow-Origin":'*'
}
return config
}
}
}
4. Find the serviceWorker.js file under src and add methods, functions, and interceptions to it (if the sub-application reports an error in the main application, replace this code with your file code);
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}
The above is what the react sub-application needs to operate!