1 主应用接入
安装 yarn add qiankun
1.1微应用注入功能
java
import { registerMicroApps, start as startQiankun } from 'qiankun';
const initRegisterMicroApps = () => {
// 注册子应用
registerMicroApps([
{
name: 'scm-suppler', // 子应用名称
entry: '//localhost:3000', // 子应用入口
container: '#microApp', // 挂载子应用的容器
activeRule: '/message', // 激活路径
props: {
// 传递给子应用的参数
mainAppProp: '来自主应用的参数',
},
},
]);
const start = () => {
// 启动 qiankun
startQiankun({
sandbox: {
strictStyleIsolation: true, // 严格的样式隔离
experimentalStyleIsolation: true,
},
// 单例模式
singular: true,
// 可选配置
// prefetch: 'all', // 预加载子应用
});
};
return {
start,
};
};
export default initRegisterMicroApps;
1.2入口文件引入
java
import { createApp } from 'vue';
import './style.css';
import App from './App';
import initRegisterMicroApps from './registerMicroApps';
let app: any;
const { start } = initRegisterMicroApps();
const bootstrap = () => {
app = createApp(App).mount('#app');
};
bootstrap();
start();
2 子应用接入
vite: yarn add vite-plugin-qiankun
2.1 vite 配置
java
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import qiankun from 'vite-plugin-qiankun';
// https://vite.dev/config/
export default defineConfig({
base: '/message',
plugins: [
vue(),
vueJsx({
// JSX 插件选项
transformOn: true,
mergeProps: true,
}),
qiankun('scm-suppler', {
useDevMode: true, // 如果是开发环境这个很重要,不开会报错es6 的 module 不支持
}),
],
server: {
port: 3000,
host: '0.0.0.0',
open: true,
cors: true,
headers: {
'Access-Control-Allow-Origin': '*',
},
},
});
2.2 子应用入口文件
java
import { createApp } from 'vue';
import './style.css';
import App from './App.vue';
import {
renderWithQiankun,
qiankunWindow,
type QiankunProps,
} from 'vite-plugin-qiankun/dist/helper';
let app: any;
const bootstrap = (props: QiankunProps) => {
// 这一步很重要,否则会提示找不到哦 dom
let elDom = props?.container?.querySelector?.('#app') || '#app';
app = createApp(App).mount(elDom);
};
// some code
renderWithQiankun({
mount(props) {
console.log('mount');
debugger;
bootstrap(props);
},
update(props) {},
/**
* The bootstrap function is called when the micro app is initialized.
* It is responsible for mounting the app to the DOM.
*
* @return {void} Nothing is returned.
*/
bootstrap() {
console.log('bootstrap');
},
unmount(props: any) {
console.log('unmount');
const { container } = props;
app.unmount();
},
});
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
debugger;
bootstrap({});
}
坑点
- 开发环境一定要先启动子服务器,再启动主服务,否则会提示找不到应用,而且刷新无效,具体原因还在甄别中。